Programs & Examples On #Nscoder

The NSCoder abstract class declares the interface used by concrete subclasses to transfer objects and other Objective-C/Swift data items between memory and some other format.

How to create custom view programmatically in swift having controls text field, button etc

Swift 3 / Swift 4 Update:

let screenSize: CGRect = UIScreen.main.bounds
let myView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width - 10, height: 10))
self.view.addSubview(myView)

Custom UITableViewCell from nib in Swift

I had to make sure that when creating the outlet to specify that I was hooking to the cell, not the object's owner. When the menu appears to name it you have to select it in the 'object' dropdown menu. Of course you must declare the cell as your class too, not just 'TableViewCellClass'. Otherwise I would keep getting the class not key compliant.

How to initialize/instantiate a custom UIView class with a XIB file in Swift

And this is the answer of Frederik on Swift 3.0

/*
 Usage:
 - make your CustomeView class and inherit from this one
 - in your Xib file make the file owner is your CustomeView class
 - *Important* the root view in your Xib file must be of type UIView
 - link all outlets to the file owner
 */
@IBDesignable
class NibLoadingView: UIView {

    @IBOutlet weak var view: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        nibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        nibSetup()
    }

    private func nibSetup() {
        backgroundColor = .clear

        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.translatesAutoresizingMaskIntoConstraints = true

        addSubview(view)
    }

    private func loadViewFromNib() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
        let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView

        return nibView
    }
}

How to have stored properties in Swift, the same way I had on Objective-C?

With Obj-c Categories you can only add methods, not instance variables.

In you example you have used @property as a shortcut to adding getter and setter method declarations. You still need to implement those methods.

Similarly in Swift you can add use extensions to add instance methods, computed properties etc. but not stored properties.

Attempt to set a non-property-list object as an NSUserDefaults

I ran into this and eventually figured out it was because I was trying to use NSNumber as dictionary keys, and property lists only allow strings as keys. The documentation for setObject:forKey: doesn't mention this limitation, but the About Property Lists page that it links to does:

By convention, each Cocoa and Core Foundation object listed in Table 2-1 is called a property-list object. Conceptually, you can think of “property list” as being an abstract superclass of all these classes. If you receive a property list object from some method or function, you know that it must be an instance of one of these types, but a priori you may not know which type. If a property-list object is a container (that is, an array or dictionary), all objects contained within it must also be property-list objects. If an array or dictionary contains objects that are not property-list objects, then you cannot save and restore the hierarchy of data using the various property-list methods and functions. And although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.

(Emphasis mine)

How to store custom objects in NSUserDefaults

If anybody is looking for a swift version:

1) Create a custom class for your data

class customData: NSObject, NSCoding {
let name : String
let url : String
let desc : String

init(tuple : (String,String,String)){
    self.name = tuple.0
    self.url = tuple.1
    self.desc = tuple.2
}
func getName() -> String {
    return name
}
func getURL() -> String{
    return url
}
func getDescription() -> String {
    return desc
}
func getTuple() -> (String,String,String) {
    return (self.name,self.url,self.desc)
}

required init(coder aDecoder: NSCoder) {
    self.name = aDecoder.decodeObjectForKey("name") as! String
    self.url = aDecoder.decodeObjectForKey("url") as! String
    self.desc = aDecoder.decodeObjectForKey("desc") as! String
}

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(self.name, forKey: "name")
    aCoder.encodeObject(self.url, forKey: "url")
    aCoder.encodeObject(self.desc, forKey: "desc")
} 
}

2) To save data use following function:

func saveData()
    {
        let data  = NSKeyedArchiver.archivedDataWithRootObject(custom)
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(data, forKey:"customArray" )
    }

3) To retrieve:

if let data = NSUserDefaults.standardUserDefaults().objectForKey("customArray") as? NSData
        {
             custom = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! [customData]
        }

Note: Here I am saving and retrieving an array of the custom class objects.

How to get previous month and year relative to today, using strtotime and date?

Have a look at the DateTime class. It should do the calculations correctly and the date formats are compatible with strttotime. Something like:

$datestring='2011-03-30 first day of last month';
$dt=date_create($datestring);
echo $dt->format('Y-m'); //2011-02

C++ display stack trace on exception

AFAIK libunwind is quite portable and so far I haven't found anything easier to use.

Moment.js: Date between dates

if (date.isBefore(endDate) 
 && date.isAfter(startDate) 
 || (date.isSame(startDate) || date.isSame(endDate))

is logically the same as

if (!(date.isBefore(startDate) || date.isAfter(endDate)))

which saves you a couple of lines of code and (in some cases) method calls.

Might be easier than pulling in a whole plugin if you only want to do this once or twice.

Determining complexity for recursive functions (Big O notation)

For the case where n <= 0, T(n) = O(1). Therefore, the time complexity will depend on when n >= 0.

We will consider the case n >= 0 in the part below.

1.

T(n) = a + T(n - 1)

where a is some constant.

By induction:

T(n) = n * a + T(0) = n * a + b = O(n)

where a, b are some constant.

2.

T(n) = a + T(n - 5)

where a is some constant

By induction:

T(n) = ceil(n / 5) * a + T(k) = ceil(n / 5) * a + b = O(n)

where a, b are some constant and k <= 0

3.

T(n) = a + T(n / 5)

where a is some constant

By induction:

T(n) = a * log5(n) + T(0) = a * log5(n) + b = O(log n)

where a, b are some constant

4.

T(n) = a + 2 * T(n - 1)

where a is some constant

By induction:

T(n) = a + 2a + 4a + ... + 2^(n-1) * a + T(0) * 2^n 
     = a * 2^n - a + b * 2^n
     = (a + b) * 2^n - a
     = O(2 ^ n)

where a, b are some constant.

5.

T(n) = n / 2 + T(n - 5)

where n is some constant

Rewrite n = 5q + r where q and r are integer and r = 0, 1, 2, 3, 4

T(5q + r) = (5q + r) / 2 + T(5 * (q - 1) + r)

We have q = (n - r) / 5, and since r < 5, we can consider it a constant, so q = O(n)

By induction:

T(n) = T(5q + r)
     = (5q + r) / 2 + (5 * (q - 1) + r) / 2 + ... + r / 2 +  T(r)
     = 5 / 2 * (q + (q - 1) + ... + 1) +  1 / 2 * (q + 1) * r + T(r)
     = 5 / 4 * (q + 1) * q + 1 / 2 * (q + 1) * r + T(r)
     = 5 / 4 * q^2 + 5 / 4 * q + 1 / 2 * q * r + 1 / 2 * r + T(r)

Since r < 4, we can find some constant b so that b >= T(r)

T(n) = T(5q + r)
     = 5 / 2 * q^2 + (5 / 4 + 1 / 2 * r) * q + 1 / 2 * r + b
     = 5 / 2 * O(n ^ 2) + (5 / 4 + 1 / 2 * r) * O(n) + 1 / 2 * r + b
     = O(n ^ 2)

MySQL LIKE IN()?

This would be correct:

SELECT * FROM table WHERE field regexp concat_ws("|",(
"111",
"222",
"333"
));

HTML form with side by side input fields

You could use the {display: inline-flex;} this would produce this: inline-flex

Cannot find Microsoft.Office.Interop Visual Studio

If you have installed latest Visual studio and want to To locate library of Microsoft.Office.Interop.Outlook or any other Microsoft.Office.Interop library then you should look into below 2 folders:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office14

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office15

Please note that folder could be C:\Program Files\

Tick symbol in HTML/XHTML

Coming very late to the party, I found that &check; (✓) worked in Opera. I haven't tested it on any other browsers, but it might be useful for some people.

Conditional operator in Python?

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

How to hide Soft Keyboard when activity starts

If you don't want to use xml, make a Kotlin Extension to hide keyboard

// In onResume, call this
myView.hideKeyboard()

fun View.hideKeyboard() {
    val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}

Alternatives based on use case:

fun Fragment.hideKeyboard() {
    view?.let { activity?.hideKeyboard(it) }
}

fun Activity.hideKeyboard() {
    // Calls Context.hideKeyboard
    hideKeyboard(currentFocus ?: View(this))
}

fun Context.hideKeyboard(view: View) {
    view.hideKeyboard()
}

How to show soft keyboard

fun Context.showKeyboard() { // Or View.showKeyboard()
    val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.toggleSoftInput(SHOW_FORCED, HIDE_IMPLICIT_ONLY)
}

Simpler method when simultaneously requesting focus on an edittext

myEdittext.focus()

fun View.focus() {
    requestFocus()
    showKeyboard()
}

Bonus simplification:

Remove requirement for ever using getSystemService: Splitties Library

// Simplifies above solution to just
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)

Is there any way to wait for AJAX response and halt execution?

use async:false attribute along with url and data. this will help to execute ajax call immediately and u can fetch and use data from server.

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        async:false
        success: function(data) {
            return data;
        }
    });
}

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

Answer seems to be a little old, What I did was to use this mapper to convert a MAP

      ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);

a simple Map:

          Map<String, Object> user = new HashMap<String,Object>();
            user.put( "id",  teklif.getAccount().getId() );
            user.put( "fname", teklif.getAccount().getFname());
            user.put( "lname", teklif.getAccount().getLname());
            user.put( "email", teklif.getAccount().getEmail());
            user.put( "test", null);

Use it like this for example:

      String json = mapper.writeValueAsString(user);

How to filter by string in JSONPath?

Your query looks fine, and your data and query work for me using this JsonPath parser. Also see the example queries on that page for more predicate examples.

The testing tool that you're using seems faulty. Even the examples from the JsonPath site are returning incorrect results:

e.g., given:

{
    "store":
    {
        "book":
        [ 
            { "category": "reference",
              "author": "Nigel Rees",
              "title": "Sayings of the Century",
              "price": 8.95
            },
            { "category": "fiction",
              "author": "Evelyn Waugh",
              "title": "Sword of Honour",
              "price": 12.99
            },
            { "category": "fiction",
              "author": "Herman Melville",
              "title": "Moby Dick",
              "isbn": "0-553-21311-3",
              "price": 8.99
            },
            { "category": "fiction",
              "author": "J. R. R. Tolkien",
              "title": "The Lord of the Rings",
              "isbn": "0-395-19395-8",
              "price": 22.99
            }
        ],
        "bicycle":
        {
            "color": "red",
            "price": 19.95
        }
    }
}

And the expression: $.store.book[?(@.length-1)].title, the tool returns a list of all titles.

Get element of JS object with an index

var myobj = {"A":["Abe"], "B":["Bob"]};

var keysArray = Object.keys(myobj);

var valuesArray = Object.keys(myobj).map(function(k) {

   return String(myobj[k]);

});

var mydata = valuesArray[keysArray.indexOf("A")]; // Abe

Local dependency in package.json

If you want to further automate this, because you are checking your module into version control, and don't want to rely upon devs remembering to npm link, you can add this to your package.json "scripts" section:

"scripts": {
    "postinstall": "npm link ../somelocallib",
    "postupdate": "npm link ../somelocallib"
  }

This feels beyond hacky, but it seems to "work". Got the tip from this npm issue: https://github.com/npm/npm/issues/1558#issuecomment-12444454

How to do a background for a label will be without color?

If you picture box in the background then use this:

label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent;

Put this code below InitializeComponent(); or in Form_Load Method.

Ref: https://www.c-sharpcorner.com/blogs/how-to-make-a-transparent-label-over-a-picturebox1

PHP preg_match - only allow alphanumeric strings and - _ characters

Code:

if(preg_match('/[^a-z_\-0-9]/i', $string))
{
  echo "not valid string";
}

Explanation:

  • [] => character class definition
  • ^ => negate the class
  • a-z => chars from 'a' to 'z'
  • _ => underscore
  • - => hyphen '-' (You need to escape it)
  • 0-9 => numbers (from zero to nine)

The 'i' modifier at the end of the regex is for 'case-insensitive' if you don't put that you will need to add the upper case characters in the code before by doing A-Z

Best way to iterate through a Perl array

IMO, implementation #1 is typical and being short and idiomatic for Perl trumps the others for that alone. A benchmark of the three choices might offer you insight into speed, at least.

In Jenkins, how to checkout a project into a specific directory (using GIT)

The default git plugin for Jenkins does the job quite nicely.

After adding a new git repository (project configuration > Source Code Management > check the GIT option) to the project navigate to the bottom of the plugin settings, just above Repository browser region. There should be an Advanced button. After clicking it a new form should appear, with a value described as Local subdirectory for repo (optional). Setting this to folder will make the plugin to check out the repository into the folder relative to your workspace. This way you can have as many repositories in your project as you need, all in separate locations.

Alternatively, if the project you're using will allow that, you can use GIT sub modules, which are similar to external paths in SVN. In the GIT Book there is a section on that very topic. If that will not be against some policy, submodules are fairly simple to use, giving you powerful way to control the locations, versions/tags/branches that will be imported AND it will be available on your local repository as well giving you better portability.

Obviously the GIT plugin supports checking out submodules, so Jenkins can work with them quite effectively.

Rails DB Migration - How To Drop a Table?

Write your migration manually. E.g. run rails g migration DropUsers.

As for the code of the migration I'm just gonna quote Maxwell Holder's post Rails Migration Checklist

BAD - running rake db:migrate and then rake db:rollback will fail

class DropUsers < ActiveRecord::Migration
  def change
    drop_table :users
  end
end

GOOD - reveals intent that migration should not be reversible

class DropUsers < ActiveRecord::Migration
  def up
    drop_table :users
  end

  def down
    fail ActiveRecord::IrreversibleMigration
  end
end

BETTER - is actually reversible

class DropUsers < ActiveRecord::Migration
  def change
    drop_table :users do |t|
      t.string :email, null: false
      t.timestamps null: false
    end
  end
end

Display html text in uitextview

BHUPI's answer is correct, but if you would like to combine your custom font from UILabel or UITextView with HTML content, you need to correct your html a bit:

NSString *htmlString = @"<b>Bold</b><br><i>Italic</i><p> <del>Deleted</del><p>List<ul><li>Coffee</li><li type='square'>Tea</li></ul><br><a href='URL'>Link </a>";

htmlString = [htmlString stringByAppendingString:@"<style>body{font-family:'YOUR_FONT_HERE'; font-size:'SIZE';}</style>"];
/*Example:

 htmlString = [htmlString stringByAppendingString:[NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx;}</style>",_myLabel.font.fontName,_myLabel.font.pointSize]];
*/
 NSAttributedString *attributedString = [[NSAttributedString alloc]
                      initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
                           options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                documentAttributes: nil
                             error: nil
            ];
textView.attributedText = attributedString;

You can see the difference on the picture below: enter image description here

Android Service needs to run always (Never pause or stop)

In order to start a service in its own process, you must specify the following in the xml declaration.

<service
  android:name="WordService"
  android:process=":my_process" 
  android:icon="@drawable/icon"
  android:label="@string/service_name"
  >
</service> 

Here you can find a good tutorial that was really useful to me

http://www.vogella.com/articles/AndroidServices/article.html

Hope this helps

How to retrieve value from elements in array using jQuery?

Use: http://jsfiddle.net/xH79d/

var n = $("input[name^='card']").length;
var array = $("input[name^='card']");

for(i=0; i < n; i++) {

   // use .eq() within a jQuery object to navigate it by Index

   card_value = array.eq(i).attr('name'); // I'm assuming you wanted -name-
   // otherwise it'd be .eq(i).val(); (if you wanted the text value)
   alert(card_value);
}

?

javascript createElement(), style problem

Others have given you the answer about appendChild.

Calling document.write() on a page that is not open (e.g. has finished loading) first calls document.open() which clears the entire content of the document (including the script calling document.write), so it's rarely a good idea to do that.

versionCode vs versionName in Android Manifest

I'm going to give you my interpretation of the only documentation I can find on the subject.

"for example to check an upgrade or downgrade relationship." <- You can downgrade an app.

"you should make sure that each successive release of your application uses a greater value. The system does not enforce this behavior" <- The number really should increase, but you can still downgrade an app.

android:versionCode — An integer value that represents the version of the application code, relative to other versions. The value is an integer so that other applications can programmatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any integer you want, however you should make sure that each successive release of your application uses a greater value. The system does not enforce this behavior, but increasing the value with successive releases is normative. Typically, you would release the first version of your application with versionCode set to 1, then monotonically increase the value with each release, regardless whether the release constitutes a major or minor release. This means that the android:versionCode value does not necessarily have a strong resemblance to the application release version that is visible to the user (see android:versionName, below). Applications and publishing services should not display this version value to users.

background:none vs background:transparent what is the difference?

To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent and background-image: none) without explicitly specifying any value such as transparent or none, you can do so by writing:

background: initial;

Algorithm to randomly generate an aesthetically-pleasing color palette

An answer that shouldn't be overlooked, because it's simple and presents advantages, is sampling of real life photos and paintings. sample as many random pixels as you want random colors on thumbnails of modern art pics, cezanne, van gogh, monnet, photos... the advantage is that you can get colors by theme and that they are organic colors. just put 20 - 30 pics in a folder and random sample a random pic every time.

Conversion to HSV values is a widespread code algorithm for psychologically based palette. hsv is easier to randomize.

mysql count group by having

One way would be to use a nested query:

SELECT count(*)
FROM (
   SELECT COUNT(Genre) AS count
   FROM movies
   GROUP BY ID
   HAVING (count = 4)
) AS x

The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.

Why would an Enum implement an Interface?

Enums are just classes in disguise, so for the most part, anything you can do with a class you can do with an enum.

I cannot think of a reason that an enum should not be able to implement an interface, at the same time I cannot think of a good reason for them to either.

I would say once you start adding thing like interfaces, or method to an enum you should really consider making it a class instead. Of course I am sure there are valid cases for doing non-traditional enum things, and since the limit would be an artificial one, I am in favour of letting people do what they want there.

How to install gdb (debugger) in Mac OSX El Capitan?

This doesn't necessarily address the question but if you are using Mac OS X then you can probably use lldb LLDB Homepage . It's very similar to gdb and even provides a guide to using commands that you would use on gdb.

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

use keyof typeof

const cat = {
    name: 'tuntun'
}

const key: string = 'name' 

cat[key as keyof typeof cat]

Install windows service without InstallUtil.exe

Not double click, you run it with the correct command line parameters, so type something like MyService -i and then MyService -u to uninstall it`.

You could otherwise use sc.exe to install and uninstall it (or copy along InstallUtil.exe).

Func delegate with no return type

All Func delegates return something; all the Action delegates return void.

Func<TResult> takes no arguments and returns TResult:

public delegate TResult Func<TResult>()

Action<T> takes one argument and does not return a value:

public delegate void Action<T>(T obj)

Action is the simplest, 'bare' delegate:

public delegate void Action()

There's also Func<TArg1, TResult> and Action<TArg1, TArg2> (and others up to 16 arguments). All of these (except for Action<T>) are new to .NET 3.5 (defined in System.Core).

How to ftp with a batch file?

You can use PowerShell as well; this is what I did. As I needed to download a file based on a pattern I dynamically created a command file and then let ftp do the rest.

I used basic PowerShell commands. I did not need to download any additional components. I first checked if the requisite number of files existed. If they I invoked the FTP the second time with an Mget. I run this from a Windows Server 2008 connecting to a Windows XP remote server.

function make_ftp_command_file($p_file_pattern,$mget_flag)
{
    # This function dynamically prepares the FTP file.
    # The file needs to be prepared daily because the
    # pattern changes daily.
    # PowerShell default encoding is Unicode.
    # Unicode command files are not compatible with FTP so
    # we need to make sure we create an ASCII file.

    write-output "USER" | out-file -filepath C:\fc.txt -encoding ASCII
    write-output "ftpusername" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    write-output "password" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    write-output "ASCII" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    If ($mget_flag -eq "Y")
    {
        write-output "prompt" | out-file -filepath C:\fc.txt -encoding ASCII -Append
        write-output "mget $p_file_pattern" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    }
    else
    {
        write-output "ls $p_file_pattern" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    }

    write-output quit | out-file -filepath C:\fc.txt -encoding ASCII -Append
}


###########################  Init Section ###############################
$yesterday = (get-date).AddDays(-1)
$yesterday_fmt = date $yesterday -format "yyyyMMdd"
$file_pattern = "BRAE_GE_*" + $yesterday_fmt + "*.csv"
$file_log = $yesterday_fmt + ".log"

echo  $file_pattern
echo  $file_log


############################## Main Section ############################
# Change location to folder where the files need to be downloaded
cd c:\remotefiles

# Dynamically create the FTP Command to get a list of files from
# the remote servers
echo "Call function that creates a FTP Command "
make_ftp_command_file $file_pattern N


#echo "Connect to remote site via FTP"
# Connect to Remote Server and get file listing
ftp -n -v -s:C:\Clover\scripts\fc.txt 10.129.120.31 > C:\logs\$file_log

$matches=select-string -pattern "BRAE_GE_[A-Z][A-Z]*" C:\logs\$file_log

# Check if the required number of Files available for download
if ($matches.count -eq 36)
{
    # Create the FTP command file

    # This time the command file has an mget rather than an ls
    make_ftp_command_file $file_pattern Y

    # Change directory if not done so
    cd c:\remotefiles

    # Invoke ftp with newly created command file
    ftp -n -v -s:C:\Clover\scripts\fc.txt 10.129.120.31 > C:\logs\$file_log
}
else
{
    echo "The full set of files is not available"
}

Pass a JavaScript function as parameter

You can also use eval() to do the same thing.

//A function to call
function needToBeCalled(p1, p2)
{
    alert(p1+"="+p2);
}

//A function where needToBeCalled passed as an argument with necessary params
//Here params is comma separated string
function callAnotherFunction(aFunction, params)
{
    eval(aFunction + "("+params+")");
}

//A function Call
callAnotherFunction("needToBeCalled", "10,20");

That's it. I was also looking for this solution and tried solutions provided in other answers but finally got it work from above example.

Datatable date sorting dd/mm/yyyy issue

Problem source is datetime format.

Wrong samples: "MM-dd-yyyy H:mm","MM-dd-yyyy"

Correct sample: "MM-dd-yyyy HH:mm"

How to keep onItemSelected from firing off on a newly instantiated Spinner?

I would try to call

spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

after you call setAdapter(). Also try out calling before the adapter.

You always have the solution to go with subclassing, where you can wrap a boolean flag to your overriden setAdapter method to skip the event.

Set opacity of background image without affecting child elements

Another option is CSS Tricks approach of inserting a pseudo element the exact size of the original element right behind it to fake the opaque background effect that we're looking for. Sometimes you will need to set a height for the pseudo element.

div {
  width: 200px;
  height: 200px;
  display: block;
  position: relative;
}

div::after {
  content: "";
  background: url(image.jpg);
  opacity: 0.5;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  z-index: -1;   
}

How to make button look like a link?

I think this is very easy to do with very few lines. here is my solution

_x000D_
_x000D_
.buttonToLink{
   background: none;
   border: none;
   color: red
}

.buttonToLink:hover{
   background: none;
   text-decoration: underline;
}
_x000D_
<button  class="buttonToLink">A simple link button</button>
_x000D_
_x000D_
_x000D_

Prevent form redirect OR refresh on submit?

In the opening tag of your form, set an action attribute like so:

<form id="contactForm" action="#">

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

You don't need Xvfb

It is failing to start due to a mismatch between the chrome version and the chromedriver version. Downloading and installing the same versions or latest versions would solve the issue.

PPT to PNG with transparent background

One workaround that I have done is:

  • Ctrl + a to select everything in the slide
  • Ctrl + c to copy it
  • open GIMP (probably works in Photoshop or other software)
  • make a new image with a transparent background
  • Ctrl + v to paste all the vectors/text into the image
  • Export the image to a PNG or whatever format

It looks pretty much exactly the same as in Powerpoint, and the vectors/text are very clean with their transparency edges.

Case insensitive comparison NSString

Alternate solution for swift:

To make both UpperCase:

e.g:

if ("ABcd".uppercased() == "abcD".uppercased()){
}

or to make both LowerCase:

e.g:

if ("ABcd".lowercased() == "abcD".lowercased()){
}

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Python how to write to a binary file?

As of Python 3.2+, you can also accomplish this using the to_bytes native int method:

newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
    newFile.write(byte.to_bytes(1, byteorder='big'))

I.e., each single call to to_bytes in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte. You can also shorten the last two lines into a single one:

newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))

Pass array to ajax request in $.ajax()

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});

bool to int conversion

int x = 4<5;

Completely portable. Standard conformant. bool to int conversion is implicit!

§4.7/4 from the C++ Standard says (Integral Conversion)

If the source type is bool, the value false is converted to zero and the value true is converted to one.


As for C, as far as I know there is no bool in C. (before 1999) So bool to int conversion is relevant in C++ only. In C, 4<5 evaluates to int value, in this case the value is 1, 4>5 would evaluate to 0.

EDIT: Jens in the comment said, C99 has _Bool type. bool is a macro defined in stdbool.h header file. true and false are also macro defined in stdbool.h.

§7.16 from C99 says,

The macro bool expands to _Bool.

[..] true which expands to the integer constant 1, false which expands to the integer constant 0,[..]

react-native :app:installDebug FAILED

For me, restarting my phone did the trick.

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

Date validation with ASP.NET validator

I believe that the dates have to be specified in the current culture of the application. You might want to experiment with setting CultureInvariantValues to true and see if that solves your problem. Otherwise you may need to change the DateTimeFormat for the current culture (or the culture itself) to get what you want.

Wait one second in running program

Try this function

public void Wait(int time) 
{           
    Thread thread = new Thread(delegate()
    {   
        System.Threading.Thread.Sleep(time);
    });
    thread.Start();
    while (thread.IsAlive)
    Application.DoEvents();
}

Call function

Wait(1000); // Wait for 1000ms = 1s

Calling a class method raises a TypeError in Python

You need to spend a little more time on some fundamentals of object-oriented programming.

This sounds harsh, but it's important.

  • Your class definition is incorrect -- although the syntax happens to be acceptable. The definition is simply wrong.

  • Your use of the class to create an object is entirely missing.

  • Your use of a class to do a calculation is inappropriate. This kind of thing can be done, but it requires the advanced concept of a @staticmehod.

Since your example code is wrong in so many ways, you can't get a tidy "fix this" answer. There are too many things to fix.

You'll need to look at better examples of class definitions. It's not clear what source material you're using to learn from, but whatever book you're reading is either wrong or incomplete.

Please discard whatever book or source you're using and find a better book. Seriously. They've mislead you on how a class definition looks and how it's used.

You might want to look at http://homepage.mac.com/s_lott/books/nonprog/htmlchunks/pt11.html for a better introduction to classes, objects and Python.

Convert JavaScript string in dot notation into an object reference

I suggest to split the path and iterate it and reduce the object you have. This proposal works with a default value for missing properties.

_x000D_
_x000D_
const getValue = (object, keys) => keys.split('.').reduce((o, k) => (o || {})[k], object);_x000D_
_x000D_
console.log(getValue({ a: { b: '1', c: '2' } }, 'a.b'));_x000D_
console.log(getValue({ a: { b: '1', c: '2' } }, 'foo.bar.baz'));
_x000D_
_x000D_
_x000D_

How to retrieve element value of XML using Java?

There are a number of different ways to do this. You might want to check out XStream or JAXB. There are tutorials and the examples.

Accessing dict_keys element by index in Python3

I wanted "key" & "value" pair of a first dictionary item. I used the following code.

 key, val = next(iter(my_dict.items()))

Regex Match all characters between two strings

For example

(?<=This is)(.*)(?=sentence)

Regexr

I used lookbehind (?<=) and look ahead (?=) so that "This is" and "sentence" is not included in the match, but this is up to your use case, you can also simply write This is(.*)sentence.

The important thing here is that you activate the "dotall" mode of your regex engine, so that the . is matching the newline. But how you do this depends on your regex engine.

The next thing is if you use .* or .*?. The first one is greedy and will match till the last "sentence" in your string, the second one is lazy and will match till the next "sentence" in your string.

Update

Regexr

This is(?s)(.*)sentence

Where the (?s) turns on the dotall modifier, making the . matching the newline characters.

Update 2:

(?<=is \()(.*?)(?=\s*\))

is matching your example "This is (a simple) sentence". See here on Regexr

Android Fragment handle back button press

If you want to handle hardware Back key event than you have to do following code in your onActivityCreated() method of Fragment.

You also need to check Action_Down or Action_UP event. If you will not check then onKey() Method will call 2 times.

Also, If your rootview(getView()) will not contain focus then it will not work. If you have clicked on any control then again you need to give focus to rootview using getView().requestFocus(); After this only onKeydown() will call.

getView().setFocusableInTouchMode(true);
getView().requestFocus();

getView().setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        Toast.makeText(getActivity(), "Back Pressed", Toast.LENGTH_SHORT).show();
                    return true;
                    }
                }
                return false;
            }
        });

Working very well for me.

How can I remove or replace SVG content?

Setting the id attribute when appending the svg element can also let d3 select so remove() later on this element by id :

var svg = d3.select("theParentElement").append("svg")
.attr("id","the_SVG_ID")
.attr("width",...

...

d3.select("#the_SVG_ID").remove();

Using node.js as a simple web server

There are already some great solutions for a simple nodejs server. There is a one more solution if you need live-reloading as you made changes to your files.

npm install lite-server -g

navigate your directory and do

lite-server

it will open browser for you with live-reloading.

What to do on TransactionTooLargeException

This was happening in my app because I was passing a list of search results in a fragment's arguments, assigning that list to a property of the fragment - which is actually a reference to the same location in memory pointed to by the fragment's arguments - then adding new items to the list, which also changed the size of the fragment's arguments. When the activity is suspended, the base fragment class tries to save the fragment's arguments in onSaveInstanceState, which crashes if the arguments are larger than 1MB. For example:

private ArrayList<SearchResult> mSearchResults;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (getArguments() != null && getArguments().getSerializable("SearchResults") != null) {
        mSearchResults = (ArrayList) getArguments().getSerializable("SearchResults");
    }
}

private void onSearchResultsObtained(ArrayList<SearchResult> pSearchResults) {

    // Because mSearchResults points to the same location in memory as the fragment's arguments
    // this will also increase the size of the arguments!
    mSearchResults.addAll(pSearchResults);
}

The easiest solution in this case was to assign a copy of the list to the fragment's property instead of assigning a reference:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (getArguments() != null && getArguments().getSerializable("SearchResults") != null) {

        // Copy value of array instead of reference
        mSearchResults = new ArrayList((ArrayList) getArguments().getSerializable("SearchResults"));
    }
}

An even better solution would be to not pass around so much data in the arguments.

I probably never would have found this without the help of this answer and TooLargeTool.

Shared folder between MacOSX and Windows on Virtual Box

Yesterday, I am able to share the folders from my host OS Macbook (high Sierra) to Guest OS Windows 10

Original Answer

Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:

  1. VirtualBox Manager: Open the Shared Folders setting and click the '+' icon to add a new folder. Then, populate the Folder Path (or use the drop-down to navigate) with the folder you want shared and make sure "Auto-Mount" and "Make Permanent" are checked.
  2. Boot Windows
  3. Download the VBoxGuestAdditions_4.0.12.iso from http://download.virtualbox.org/virtualbox/4.0.12/
  4. Go to Devices > Optical drives > choose disk image.. choose the one downloaded in step 3
  5. Inside host guest OS (Windows 10, in my case) I could see: This PC > CD Drive (D:) Virtual Guest Additions

For now, right click on it, select Properties, the Compatibility tab, and select Windows 8 compatibility there. Much easier than using the compatibility troubleshooting I did initially.

enter image description here

  1. reboot the guest OS (Windows 10)
  2. Inside host guest OS, you could see the shared folder This PC> shared folder

It worked for me so I thought of sharing with everyone too.

How to check if an object is a certain type

In VB.NET, you need to use the GetType method to retrieve the type of an instance of an object, and the GetType() operator to retrieve the type of another known type.

Once you have the two types, you can simply compare them using the Is operator.

So your code should actually be written like this:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then

    End If
    Obj.DataBind()
End Sub

You can also use the TypeOf operator instead of the GetType method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:

If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then

End If

Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.

How to get the list of all installed color schemes in Vim?

Type

:colorscheme then Space followed by TAB.

or as Peter said,

:colorscheme then Space followed by CTRLd

The short version of the command is :colo so you can use it in the two previous commands, instead of using the "long form".

If you want to find and preview more themes, there are various websites like Vim colors

JPA OneToMany not deleting child

Here cascade, in the context of remove, means that the children are removed if you remove the parent. Not the association. If you are using Hibernate as your JPA provider, you can do it using hibernate specific cascade.

Test for existence of nested JavaScript object key

Now we can also use reduce to loop through nested keys:

_x000D_
_x000D_
// @params o<object>_x000D_
// @params path<string> expects 'obj.prop1.prop2.prop3'_x000D_
// returns: obj[path] value or 'false' if prop doesn't exist_x000D_
_x000D_
const objPropIfExists = o => path => {_x000D_
  const levels = path.split('.');_x000D_
  const res = (levels.length > 0) _x000D_
    ? levels.reduce((a, c) => a[c] || 0, o)_x000D_
    : o[path];_x000D_
  return (!!res) ? res : false_x000D_
}_x000D_
_x000D_
const obj = {_x000D_
  name: 'Name',_x000D_
  sys: { country: 'AU' },_x000D_
  main: { temp: '34', temp_min: '13' },_x000D_
  visibility: '35%'_x000D_
}_x000D_
_x000D_
const exists = objPropIfExists(obj)('main.temp')_x000D_
const doesntExist = objPropIfExists(obj)('main.temp.foo.bar.baz')_x000D_
_x000D_
console.log(exists, doesntExist)
_x000D_
_x000D_
_x000D_

How can I make all images of different height and width the same via CSS?

Updated answer (No IE11 support)

_x000D_
_x000D_
img {_x000D_
    float: left;_x000D_
    width:  100px;_x000D_
    height: 100px;_x000D_
    object-fit: cover;_x000D_
}
_x000D_
<img src="http://i.imgur.com/tI5jq2c.jpg">_x000D_
<img src="http://i.imgur.com/37w80TG.jpg">_x000D_
<img src="http://i.imgur.com/B1MCOtx.jpg">
_x000D_
_x000D_
_x000D_

Original answer

_x000D_
_x000D_
.img {_x000D_
    float: left;_x000D_
    width:  100px;_x000D_
    height: 100px;_x000D_
    background-size: cover;_x000D_
}
_x000D_
<div class="img" style="background-image:url('http://i.imgur.com/tI5jq2c.jpg');"></div>_x000D_
<div class="img" style="background-image:url('http://i.imgur.com/37w80TG.jpg');"></div>_x000D_
<div class="img" style="background-image:url('http://i.imgur.com/B1MCOtx.jpg');"></div>
_x000D_
_x000D_
_x000D_

How to add 20 minutes to a current date?

var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+20);

How to calculate number of days between two dates

http://momentjs.com/ or https://date-fns.org/

From Moment docs:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days')   // =1

or to include the start:

a.diff(b, 'days')+1   // =2

Beats messing with timestamps and time zones manually.

Depending on your specific use case, you can either

  1. Use a/b.startOf('day') and/or a/b.endOf('day') to force the diff to be inclusive or exclusive at the "ends" (as suggested by @kotpal in the comments).
  2. Set third argument true to get a floating point diff which you can then Math.floor, Math.ceil or Math.round as needed.
  3. Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60.

How to test whether a service is running from the command line

I've found this:

  sc query "ServiceName" | findstr RUNNING  

seems to do roughly the right thing. But, I'm worried that's not generalized enough to work on non-english operating systems.

How can I execute PHP code from the command line?

Using PHP from the command line

Use " instead of ' on Windows when using the CLI version with -r:

php -r "echo 1;"

-- correct

php -r 'echo 1;'

-- incorrect

  PHP Parse error:  syntax error, unexpected ''echo' (T_ENCAPSED_AND_WHITESPACE), expecting end of file in Command line code on line 1

Don't forget the semicolon to close the line.

Detecting endianness programmatically in a C++ program

How about this?

#include <cstdio>

int main()
{
    unsigned int n = 1;
    char *p = 0;

    p = (char*)&n;
    if (*p == 1)
        std::printf("Little Endian\n");
    else 
        if (*(p + sizeof(int) - 1) == 1)
            std::printf("Big Endian\n");
        else
            std::printf("What the crap?\n");
    return 0;
}

Run batch file from Java code

import java.lang.Runtime;

Process run = Runtime.getRuntime().exec("cmd.exe", "/c", "Start", "path of the bat file");

This will work for you and is easy to use.

Duplicate and rename Xcode project & associated folders

For anybody else having issues with storyboard crashes after copying your project, head over to Main.storyboard under Identity Inspector.

Next, check that your current module is the correct renamed module and not the old one.

How do I check out a remote Git branch?

git checkout -b "Branch_name" [ B means Create local branch]

git branch --all

git checkout -b "Your Branch name"

git branch

successfully checkout from the master branch to dev branch

enter image description here

Create Generic method constraining T to an Enum

Hope this is helpful:

public static TValue ParseEnum<TValue>(string value, TValue defaultValue)
                  where TValue : struct // enum 
{
      try
      {
            if (String.IsNullOrEmpty(value))
                  return defaultValue;
            return (TValue)Enum.Parse(typeof (TValue), value);
      }
      catch(Exception ex)
      {
            return defaultValue;
      }
}

Init method in Spring Controller (annotation version)

public class InitHelloWorld implements BeanPostProcessor {

   public Object postProcessBeforeInitialization(Object bean,
             String beanName) throws BeansException {
       System.out.println("BeforeInitialization : " + beanName);
       return bean;  // you can return any other object as well
   }

   public Object postProcessAfterInitialization(Object bean,
             String beanName) throws BeansException {
       System.out.println("AfterInitialization : " + beanName);
       return bean;  // you can return any other object as well
   }

}

Vim for Windows - What do I type to save and exit from a file?

Esc to make sure you exit insert mode, then :wq (colon w q) or ZZ (shift-Z shift-Z).

Syntax behind sorted(key=lambda: ...)

One more example of usage sorted() function with key=lambda. Let's consider you have a list of tuples. In each tuple you have a brand, model and weight of the car and you want to sort this list of tuples by brand, model or weight. You can do it with lambda.

cars = [('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000), ('bmw', 'x5', 1700)]

print(sorted(cars, key=lambda car: car[0]))
print(sorted(cars, key=lambda car: car[1]))
print(sorted(cars, key=lambda car: car[2]))

Results:

[('bmw', 'x5', '1700'), ('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000)]
[('lincoln', 'navigator', 2000), ('bmw', 'x5', '1700'), ('citroen', 'xsara', 1100)]
[('citroen', 'xsara', 1100), ('bmw', 'x5', 1700), ('lincoln', 'navigator', 2000)]

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

Either your data is bad, or it's not structured the way you think it is. Possibly both.

To prove/disprove this hypothesis, run this query:

SELECT * from
(
    SELECT count(*) as c, Supplier_Item.SKU
    FROM Supplier_Item
    INNER JOIN orderdetails
        ON Supplier_Item.sku = orderdetails.sku
    INNER JOIN Supplier
        ON Supplier_item.supplierID = Supplier.SupplierID
    GROUP BY Supplier_Item.SKU
) x
WHERE c > 1
ORDER BY c DESC

If this returns just a few rows, then your data is bad. If it returns lots of rows, then your data is not structured the way you think it is. (If it returns zero rows, I'm wrong.)

I'm guessing that you have orders containing the same SKU multiple times (two separate line items, both ordering the same SKU).

NSDate get year/month/day

    NSDate *currDate = [NSDate date];
    NSCalendar*       calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents* components = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:currDate];
    NSInteger         day = [components day];
    NSInteger         month = [components month];
    NSInteger         year = [components year];
    NSLog(@"%d/%d/%d", day, month, year);

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I usually use git on my linux machine, but at work I have to use Windows. I had the same problem when trying to commit the first commit in a Windows environment.

For those still facing this problem, I was able to resolve it as follows:

$ git commit --allow-empty -n -m "Initial commit".

Converting byte array to string in javascript

Didn't find any solution that would work with UTF-8 characters. String.fromCharCode is good until you meet 2 byte character.

For example Hüser will come as [0x44,0x61,0x6e,0x69,0x65,0x6c,0x61,0x20,0x48,0xc3,0xbc,0x73,0x65,0x72]

But if you go through it with String.fromCharCode you will have Hüser as each byte will be converted to a char separately.

Solution

Currently I'm using following solution:

function pad(n) { return (n.length < 2 ? '0' + n : n); }
function decodeUtf8(data) {
  return decodeURIComponent(
    data.map(byte => ('%' + pad(byte.toString(16)))).join('')
  );
}

Credit card expiration dates - Inclusive or exclusive?

How do time zones factor in this analysis. Does a card expire in New York before California? Does it depend on the billing or shipping addresses?

How to check String in response body with mockMvc

Here is an example how to parse JSON response and even how to send a request with a bean in JSON form:

  @Autowired
  protected MockMvc mvc;

  private static final ObjectMapper MAPPER = new ObjectMapper()
    .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    .registerModule(new JavaTimeModule());

  public static String requestBody(Object request) {
    try {
      return MAPPER.writeValueAsString(request);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }
  }

  public static <T> T parseResponse(MvcResult result, Class<T> responseClass) {
    try {
      String contentAsString = result.getResponse().getContentAsString();
      return MAPPER.readValue(contentAsString, responseClass);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Test
  public void testUpdate() {
    Book book = new Book();
    book.setTitle("1984");
    book.setAuthor("Orwell");
    MvcResult requestResult = mvc.perform(post("http://example.com/book/")
      .contentType(MediaType.APPLICATION_JSON)
      .content(requestBody(book)))
      .andExpect(status().isOk())
      .andReturn();
    UpdateBookResponse updateBookResponse = parseResponse(requestResult, UpdateBookResponse.class);
    assertEquals("1984", updateBookResponse.getTitle());
    assertEquals("Orwell", updateBookResponse.getAuthor());
  }

As you can see here the Book is a request DTO and the UpdateBookResponse is a response object parsed from JSON. You may want to change the Jackson's ObjectMapper configuration.

Is not an enclosing class Java

What I would suggest is not converting the non-static class to a static class because in that case, your inner class can't access the non-static members of outer class.

Example :

class Outer
{
    class Inner
    {
        //...
    }
}

So, in such case, you can do something like:

Outer o = new Outer();
Outer.Inner obj = o.new Inner();

Show a PDF files in users browser via PHP/Perl

    $url ="https://yourFile.pdf";
    $content = file_get_contents($url);

    header('Content-Type: application/pdf');
    header('Content-Length: ' . strlen($content));
    header('Content-Disposition: inline; filename="YourFileName.pdf"');
    header('Cache-Control: private, max-age=0, must-revalidate');
    header('Pragma: public');
    ini_set('zlib.output_compression','0');

    die($content);

Tested and works fine. If you want the file to download instead, replace

    Content-Disposition: inline

with

    Content-Disposition: attachment

Change background color of selected item on a ListView

If you want to have the item remain highlighted after you have clicked it, you need to manually set it as being selected in the onItemClick listener

Android ListView selected item stay highlighted:

myList.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {   
        view.setSelected(true); // <== Will cause the highlight to remain
        //... do more stuff                          
    }});

This assumes you have a state_selected item in your selector:

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

How do I install ASP.NET MVC 5 in Visual Studio 2012?

There are a few installs you may need to apply for ASP.NET MVC 5 support in Visual Studio 2012. Update 4 seems to include the Web Tools update now.

You don't have to install the full Windows 8.1 SDK if you are just looking for the option to build web applications, just the .NET Framework 4.5.1 option in the installer. The full install is about 1.1 GB, but just the .NET installer is only 72 MB.

PostgreSQL - max number of parameters in "IN" clause?

Just tried it. the answer is -> out-of-range integer as a 2-byte value: 32768

How can I let a user download multiple files when a button is clicked?

The best way to do this is to have your files zipped and link to that:

The other solution can be found here: How to make a link open multiple pages when clicked

Which states the following:

HTML:

<a href="#" class="yourlink">Download</a>

JS:

$('a.yourlink').click(function(e) {
    e.preventDefault();
    window.open('mysite.com/file1');
    window.open('mysite.com/file2');
    window.open('mysite.com/file3');
});

Having said this, I would still go with zipping the file, as this implementation requires JavaScript and can also sometimes be blocked as popups.

Handling the null value from a resultset in JAVA

The description of the getString() method says the following:

 the column value; if the value is SQL NULL, the value returned is null

That means your problem is not that the String value is null, rather some other object is, perhaps your ResultSet or maybe you closed the connection or something like this. Provide the stack trace, that would help.

Variable might not have been initialized error

because of your a and b variable is not have been initialized. You must initialized this variables for excample if you declare this variable like this int a=0; int b=0; than your code run without error.

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

After some searching, I was able to find the information_schema.routines table and the information_schema.parameters tables. Using those, one can construct a query for this purpose. LEFT JOIN, instead of JOIN, is necessary to retrieve functions without parameters.

SELECT routines.routine_name, parameters.data_type, parameters.ordinal_position
FROM information_schema.routines
    LEFT JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name
WHERE routines.specific_schema='my_specified_schema_name'
ORDER BY routines.routine_name, parameters.ordinal_position;

How can I access getSupportFragmentManager() in a fragment?

You can use getActivity().getSupportFragmentManager() anytime you want to getSupportFragmentManager.

hierarchy is Activity -> fragment. fragment is not capable of directly calling getSupportFragmentManger but Activity can . Thus, you can use getActivity to call the current activity which the fragment is in and get getSupportFragmentManager()

How do I import other TypeScript files?

If you are looking to use modules and want it to compile to a single JavaScript file you can do the following:

tsc -out _compiled/main.js Main.ts

Main.ts

///<reference path='AnotherNamespace/ClassOne.ts'/>
///<reference path='AnotherNamespace/ClassTwo.ts'/>

module MyNamespace
{
    import ClassOne = AnotherNamespace.ClassOne;
    import ClassTwo = AnotherNamespace.ClassTwo;

    export class Main
    {
        private _classOne:ClassOne;
        private _classTwo:ClassTwo;

        constructor()
        {
            this._classOne = new ClassOne();
            this._classTwo = new ClassTwo();
        }
    }
}

ClassOne.ts

///<reference path='CommonComponent.ts'/>

module AnotherNamespace
{
    export class ClassOne
    {
        private _component:CommonComponent;

        constructor()
        {
            this._component = new CommonComponent();
        }
    }
}

CommonComponent.ts

module AnotherNamespace
{
    export class CommonComponent
    {
        constructor()
        {
        }
    }
}

You can read more here: http://www.codebelt.com/typescript/javascript-namespacing-with-typescript-internal-modules/

Pro JavaScript programmer interview questions (with answers)

(I'm assuming you mean browser-side JavaScript)

Ask him why, despite his infinite knowledge of JavaScript, it is still a good idea to use existing frameworks such as jQuery, Mootools, Prototype, etc.

Answer: Good coders code, great coders reuse. Thousands of man hours have been poured into these libraries to abstract DOM capabilities away from browser specific implementations. There's no reason to go through all of the different browser DOM headaches yourself just to reinvent the fixes.

Is there an easy way to check the .NET Framework version?

Try this one:

string GetFrameWorkVersion()
    {
        return System.Runtime.InteropServices.RuntimeEnvironment.GetSystemVersion();
    }

Trim leading and trailing spaces from a string in awk

remove leading and trailing white space in 2nd column

awk 'BEGIN{FS=OFS=","}{gsub(/^[ \t]+/,"",$2);gsub(/[ \t]+$/,"",$2)}1' input.txt

another way by one gsub:

awk 'BEGIN{FS=OFS=","} {gsub(/^[ \t]+|[ \t]+$/, "", $2)}1' infile

How do I filter query objects by date range in Django?

Still relevant today. You can also do:

import dateutil
import pytz

date = dateutil.parser.parse('02/11/2019').replace(tzinfo=pytz.UTC)

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

For CSS, I found that max height of 180 is better for mobile phones landscape 320 when showing browser chrome.

.scrollable-menu {
    height: auto;
    max-height: 180px;
    overflow-x: hidden;
}

Also, to add visible scrollbars, this CSS should do the trick:

.scrollable-menu::-webkit-scrollbar {
    -webkit-appearance: none;
    width: 4px;        
}    
.scrollable-menu::-webkit-scrollbar-thumb {
    border-radius: 3px;
    background-color: lightgray;
    -webkit-box-shadow: 0 0 1px rgba(255,255,255,.75);        
}

The changes are reflected here: https://www.bootply.com/BhkCKFEELL

How to add items to a spinner in Android?

It's just to clear the adapter, add all itens and notify change like below:

  public void show(List<Object> objLIst) {
    adapter.clear();
    adapter.addAll(objLIst);
    adapter.notifyDataSetChanged(); }

client denied by server configuration

For me the following worked which is copied from example in /etc/apache2/apache2.conf:

<Directory /srv/www/default>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

Require all granted option is the solution for the first problem example in wiki.apache.org page dedicated for this issue for Apache version 2.4+.

More details about Require option can be found on official apache page for mod_authz module and on this page too. Namely:

Require all granted -> Access is allowed unconditionally.

Using Jquery Datatable with AngularJs

I know it's tempting to use drag and drop angular modules created by other devs - but actually, unless you are doing something non-standard like dynamically adding / removing rows from the ng-repeated data set by calling $http services chance are you really don't need a directive based solution, so if you do go this direction you probably just created extra watchers you don't actually need.

What this implementation provides:

  • Pagination is always correct
  • Filtering is always correct (even if you add custom filters but of course they just need to be in the same closure)

The implementation is easy. Just use angular's version of jQuery dom ready from your view's controller:

Inside your controller:

'use strict';

var yourApp = angular.module('yourApp.yourController.controller', []);

yourApp.controller('yourController', ['$scope', '$http', '$q', '$timeout', function ($scope, $http, $q, $timeout) {

    $scope.users = [
        {
            email: '[email protected]',
            name: {
                first: 'User',
                last: 'Last Name'
            },
            phone: '(416) 555-5555',
            permissions: 'Admin'
        },
        {
            email: '[email protected]',
            name: {
                first: 'First',
                last: 'Last'
            },
            phone: '(514) 222-1111',
            permissions: 'User'
        }
    ];

    angular.element(document).ready( function () {
         dTable = $('#user_table')
         dTable.DataTable();
     });

}]);

Now in your html view can do:

<div class="table table-data clear-both" data-ng-show="viewState === possibleStates[0]">
        <table id="user_table" class="users list dtable">
            <thead>
                <tr>
                    <th>E-mail</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Phone</th>
                    <th>Permissions</th>
                    <th class="blank-cell"></th>
                </tr>
            </thead>
            <tbody>
                <tr data-ng-repeat="user in users track by $index">
                    <td>{{ user.email }}</td>
                    <td>{{ user.name.first }}</td>
                    <td>{{ user.name.last }}</td>
                    <td>{{ user.phone }}</td>
                    <td>{{ user.permissions }}</td>
                    <td class="users controls blank-cell">
                        <a class="btn pointer" data-ng-click="showEditUser( $index )">Edit</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

Efficient way to remove ALL whitespace from String?

This is fastest way I know of, even though you said you didn't want to use regular expressions:

Regex.Replace(XML, @"\s+", "")

What are the various "Build action" settings in Visual Studio project properties and what do they do?

Page -- Takes the specified XAML file, and compiles into BAML, and embeds that output into the managed resource stream for your assembly (specifically AssemblyName.g.resources), Additionally, if you have the appropriate attributes on the root XAML element in the file, it will create a blah.g.cs file, which will contain a partial class of the "codebehind" for that page; this basically involves a call to the BAML goop to re-hydrate the file into memory, and to set any of the member variables of your class to the now-created items (e.g. if you put x:Name="foo" on an item, you'll be able to do this.foo.Background = Purple; or similar.

ApplicationDefinition -- similar to Page, except it goes onestep furthur, and defines the entry point for your application that will instantiate your app object, call run on it, which will then instantiate the type set by the StartupUri property, and will give your mainwindow.

Also, to be clear, this question overall is infinate in it's results set; anyone can define additional BuildActions just by building an MSBuild Task. If you look in the %systemroot%\Microsoft.net\framework\v{version}\ directory, and look at the Microsoft.Common.targets file, you should be able to decipher many more (example, with VS Pro and above, there is a "Shadow" action that allows you generate private accessors to help with unit testing private classes.

AngularJs - ng-model in a SELECT

Select's default value should be one of its value in the list. In order to load the select with default value you can use ng-options. A scope variable need to be set in the controller and that variable is assigned as ng-model in HTML's select tag.

View this plunker for any references:

http://embed.plnkr.co/hQiYqaQXrtpxQ96gcZhq/preview

Difference between arguments and parameters in Java

The term parameter refers to any declaration within the parentheses following the method/function name in a method/function declaration or definition; the term argument refers to any expression within the parentheses of a method/function call. i.e.

  1. parameter used in function/method definition.
  2. arguments used in function/method call.

Please have a look at the below example for better understanding:

package com.stackoverflow.works;

public class ArithmeticOperations {

    public static int add(int x, int y) { //x, y are parameters here
        return x + y;
    }

    public static void main(String[] args) {
        int x = 10;
        int y = 20;
        int sum = add(x, y); //x, y are arguments here
        System.out.println("SUM IS: " +sum);
    }

}

Thank you!

How to read a file in Groovy into a string?

Here you can Find some other way to do the same.

Read file.

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
def String yourData = file1.readLines();

Read Full file.

File file1 = new File("C:\Build\myfolder\myfile.txt");
def String yourData= file1.getText();

Read file Line Bye Line.

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
for (def i=0;i<=30;i++) // specify how many line need to read eg.. 30
{
 log.info file1.readLines().get(i)

}

Create a new file.

new File("C:\Temp\FileName.txt").createNewFile();

How to sum a variable by group

You can also use the dplyr package for that purpose:

library(dplyr)
x %>% 
  group_by(Category) %>% 
  summarise(Frequency = sum(Frequency))

#Source: local data frame [3 x 2]
#
#  Category Frequency
#1    First        30
#2   Second         5
#3    Third        34

Or, for multiple summary columns (works with one column too):

x %>% 
  group_by(Category) %>% 
  summarise(across(everything(), sum))

Here are some more examples of how to summarise data by group using dplyr functions using the built-in dataset mtcars:

# several summary columns with arbitrary names
mtcars %>% 
  group_by(cyl, gear) %>%                            # multiple group columns
  summarise(max_hp = max(hp), mean_mpg = mean(mpg))  # multiple summary columns

# summarise all columns except grouping columns using "sum" 
mtcars %>% 
  group_by(cyl) %>% 
  summarise(across(everything(), sum))

# summarise all columns except grouping columns using "sum" and "mean"
mtcars %>% 
  group_by(cyl) %>% 
  summarise(across(everything(), list(mean = mean, sum = sum)))

# multiple grouping columns
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(across(everything(), list(mean = mean, sum = sum)))

# summarise specific variables, not all
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(across(c(qsec, mpg, wt), list(mean = mean, sum = sum)))

# summarise specific variables (numeric columns except grouping columns)
mtcars %>% 
  group_by(gear) %>% 
  summarise(across(where(is.numeric), list(mean = mean, sum = sum)))

For more information, including the %>% operator, see the introduction to dplyr.

Index of element in NumPy array

This problem can be solved efficiently using the numpy_indexed library (disclaimer: I am its author); which was created to address problems of this type. npi.indices can be viewed as an n-dimensional generalisation of list.index. It will act on nd-arrays (along a specified axis); and also will look up multiple entries in a vectorized manner as opposed to a single item at a time.

a = np.random.rand(50, 60, 70)
i = np.random.randint(0, len(a), 40)
b = a[i]

import numpy_indexed as npi
assert all(i == npi.indices(a, b))

This solution has better time complexity (n log n at worst) than any of the previously posted answers, and is fully vectorized.

What does map(&:name) mean in Ruby?

Another cool shorthand, unknown to many, is

array.each(&method(:foo))

which is a shorthand for

array.each { |element| foo(element) }

By calling method(:foo) we took a Method object from self that represents its foo method, and used the & to signify that it has a to_proc method that converts it into a Proc.

This is very useful when you want to do things point-free style. An example is to check if there is any string in an array that is equal to the string "foo". There is the conventional way:

["bar", "baz", "foo"].any? { |str| str == "foo" }

And there is the point-free way:

["bar", "baz", "foo"].any?(&"foo".method(:==))

The preferred way should be the most readable one.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

In SpringBoot 2.1, I found another solution. Extend standard factory class method getTomcatWebServer. And then return it as a bean from anywhere.

public class CustomTomcatServletWebServerFactory extends TomcatServletWebServerFactory {

    @Override
    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
        System.setProperty("catalina.useNaming", "true");
        tomcat.enableNaming();
        return new TomcatWebServer(tomcat, getPort() >= 0);
    }
}

@Component
public class TomcatConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new CustomTomcatServletWebServerFactory();

        return factory;
    }

Loading resources from context.xml doesn't work though. Will try to find out.

Failed to execute 'createObjectURL' on 'URL':

I had the same error for the MediaStream. The solution is set a stream to the srcObject.

From the docs:

Important: If you still have code that relies on createObjectURL() to attach streams to media elements, you need to update your code to simply set srcObject to the MediaStream directly.

Change the content of a div based on selection from dropdown menu

With zero jQuery

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <style>
.inv {
    display: none;
}
    </style>
    <body>
        <select id="target">
            <option value="">Select...</option>
            <option value="content_1">Option 1</option>
            <option value="content_2">Option 2</option>
            <option value="content_3">Option 3</option>
        <select>

        <div id="content_1" class="inv">Content 1</div>
        <div id="content_2" class="inv">Content 2</div>
        <div id="content_3" class="inv">Content 3</div>
        
        <script>
            document
                .getElementById('target')
                .addEventListener('change', function () {
                    'use strict';
                    var vis = document.querySelector('.vis'),   
                        target = document.getElementById(this.value);
                    if (vis !== null) {
                        vis.className = 'inv';
                    }
                    if (target !== null ) {
                        target.className = 'vis';
                    }
            });
        </script>
    </body>
</html>

Codepen

_x000D_
_x000D_
document
  .getElementById('target')
  .addEventListener('change', function () {
    'use strict';
    var vis = document.querySelector('.vis'),   
      target = document.getElementById(this.value);
    if (vis !== null) {
      vis.className = 'inv';
    }
    if (target !== null ) {
      target.className = 'vis';
    }
});
_x000D_
.inv {
    display: none;
}
_x000D_
<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8"/>
        <title></title>
    </head>
    <body>
        <select id="target">
            <option value="">Select...</option>
            <option value="content_1">Option 1</option>
            <option value="content_2">Option 2</option>
            <option value="content_3">Option 3</option>
        <select>

        <div id="content_1" class="inv">Content 1</div>
        <div id="content_2" class="inv">Content 2</div>
        <div id="content_3" class="inv">Content 3</div>
    </body>
</html>
_x000D_
_x000D_
_x000D_

UIAlertController custom font, size, color

Swift 5.0

let titleAttrString = NSMutableAttributedString(string: "This is a title", attributes: [NSAttributedString.Key.font: UIFont(name: "CustomFontName", size: 17) as Any])
let messageAttrString = NSMutableAttributedString(string: "This is a message", attributes: [NSAttributedString.Key.font: UIFont(name: "CustomFontName", size: 13) as Any])

alertController.setValue(titleAttrString, forKey: "attributedTitle")
alertController.setValue(messageAttrString, forKey: "attributedMessage")

Is there a Java API that can create rich Word documents?

iText is really easy to use.

If you requiere doc files you can call abiword (free lightweigh multi-os text procesor) from the command line, it has several conversion format convert options.

what does "error : a nonstatic member reference must be relative to a specific object" mean?

CPMSifDlg::EncodeAndSend() method is declared as non-static and thus it must be called using an object of CPMSifDlg. e.g.

CPMSifDlg obj;
return obj.EncodeAndSend(firstName, lastName, roomNumber, userId, userFirstName, userLastName);

If EncodeAndSend doesn't use/relate any specifics of an object (i.e. this) but general for the class CPMSifDlg then declare it as static:

class CPMSifDlg {
...
  static int EncodeAndSend(...);
  ^^^^^^
};

postgresql return 0 if returned value is null

use coalesce

COALESCE(value [, ...])
The COALESCE function returns the first of its arguments that is not null.  
Null is returned only if all arguments are null. It is often
used to substitute a default value for null values when data is
retrieved for display.

Edit

Here's an example of COALESCE with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5

IMHO COALESCE should not be use with AVG because it modifies the value. NULL means unknown and nothing else. It's not like using it in SUM. In this example, if we replace AVG by SUM, the result is not distorted. Adding 0 to a sum doesn't hurt anyone but calculating an average with 0 for the unknown values, you don't get the real average.

In that case, I would add price IS NOT NULL in WHERE clause to avoid these unknown values.

Read a variable in bash with a default value

#Script for calculating various values in MB
echo "Please enter some input: "
read input_variable
echo $input_variable | awk '{ foo = $1 / 1024 / 1024 ; print foo "MB" }'

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

I think because your are using play-service 8.4.0

It required

classpath 'com.android.tools.build:gradle:2.0.0-alpha5'
classpath 'com.google.gms:google-services:2.0.0-alpha5'

you may also refer this.

The character encoding of the HTML document was not declared

Add this as a first line in the HEAD section of your HTML template

<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">

How to cancel a local git commit

Use --soft instead of --hard flag:

git reset --soft HEAD^

Android ADB devices unauthorized

  1. First Remove the adbkey and adbkey.pub from the .android directory in your Home directory.
  2. Make .android directory in your home with 710 permissions: $ chmod 710 .android/ and ownership as: chown -R <user>:<user> .android/. Ex:

    $ chmod 710 .android/
    $ chown -R ashan:ashan .android/
    
  3. Go to developer options in your mobile and tap option Revoke USB debugging authorizations

  4. Turn off all USB Debugging and Developer Options in the device and disconnect the device from your machine.

  5. Connect the device again and at first turn on the Developer Options. Then Turn on the USB debugging.

  6. At this point in your mobile, you will get a prompt for asking permission from you. Note: you must check the checkbox always accept from this …. option and click ok.

  7. Now in you machine, start the adb server: adb start-server.

  8. Hopefully when you issue the command: adb devices now, you will see your device ready authorized.

What is @RenderSection in asp.net MVC

If

(1) you have a _Layout.cshtml view like this

<html>
    <body>
        @RenderBody()

    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    @RenderSection("scripts", required: false)
</html>

(2) you have Contacts.cshtml

@section Scripts{
    <script type="text/javascript" src="~/lib/contacts.js"></script>

}
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

(3) you have About.cshtml

<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

On you layout page, if required is set to false "@RenderSection("scripts", required: false)", When page renders and user is on about page, the contacts.js doesn't render.

    <html>
        <body><div>About<div>             
        </body>
        <script type="text/javascript" src="~/lib/layout.js"></script>
    </html>

if required is set to true "@RenderSection("scripts", required: true)", When page renders and user is on ABOUT page, the contacts.js STILL gets rendered.

<html>
    <body><div>About<div>             
    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    <script type="text/javascript" src="~/lib/contacts.js"></script>
</html>

IN SHORT, when set to true, whether you need it or not on other pages, it will get rendered anyhow. If set to false, it will render only when the child page is rendered.

Recommended way to save uploaded files in a servlet application

I post my final way of doing it based on the accepted answer:

@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {

    private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
    private String uploadsDirName;

    @Override
    public void init() throws ServletException {
        super.init();
        uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            File save = new File(uploadsDirName, getFilename(part) + "_"
                + System.currentTimeMillis());
            final String absolutePath = save.getAbsolutePath();
            log.debug(absolutePath);
            part.write(absolutePath);
            sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
        }
    }

    // helpers
    private static String getFilename(Part part) {
        // courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

where :

@SuppressWarnings("serial")
class Controller extends HttpServlet {

    static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
    static ServletContext sc;
    Logger log;
    // private
    // "/WEB-INF/app.properties" also works...
    private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
    private Properties properties;

    @Override
    public void init() throws ServletException {
        super.init();
        // synchronize !
        if (sc == null) sc = getServletContext();
        log = LoggerFactory.getLogger(this.getClass());
        try {
            loadProperties();
        } catch (IOException e) {
            throw new RuntimeException("Can't load properties file", e);
        }
    }

    private void loadProperties() throws IOException {
        try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
                if (is == null)
                    throw new RuntimeException("Can't locate properties file");
                properties = new Properties();
                properties.load(is);
        }
    }

    String property(final String key) {
        return properties.getProperty(key);
    }
}

and the /WEB-INF/app.properties :

upload.location=C:/_/

HTH and if you find a bug let me know

Handling the TAB character in Java

Yes the tab character is one character. You can match it in java with "\t".

Expanding a parent <div> to the height of its children

Using something like self-clearing div is perfect for a situation like this. Then you'll just use a class on the parent... like:

<div id="parent" class="clearfix">

How do you concatenate Lists in C#?

I know this is old but I came upon this post quickly thinking Concat would be my answer. Union worked great for me. Note, it returns only unique values but knowing that I was getting unique values anyway this solution worked for me.

namespace TestProject
{
    public partial class Form1 :Form
    {
        public Form1()
        {
            InitializeComponent();

            List<string> FirstList = new List<string>();
            FirstList.Add("1234");
            FirstList.Add("4567");

            // In my code, I know I would not have this here but I put it in as a demonstration that it will not be in the secondList twice
            FirstList.Add("Three");  

            List<string> secondList = GetList(FirstList);            
            foreach (string item in secondList)
                Console.WriteLine(item);
        }

        private List<String> GetList(List<string> SortBy)
        {
            List<string> list = new List<string>();
            list.Add("One");
            list.Add("Two");
            list.Add("Three");

            list = list.Union(SortBy).ToList();

            return list;
        }
    }
}

The output is:

One
Two
Three
1234
4567

VS2010 How to include files in project, to copy them to build output directory automatically during build or publish

Try adding a reference to the missing dll's from your service/web project directly. Adding the references to a different project didn't work for me.

I only had to do this when publishing my web app because it wasn't copying all the required dll's.

Using fonts with Rails asset pipeline

I had a similar issue when I upgraded my Rails 3 app to Rails 4 recently. My fonts were not working properly as in the Rails 4+, we are only allowed to keep the fonts under app/assets/fonts directory. But my Rails 3 app had a different font organization. So I had to configure the app so that it still works with Rails 4+ having my fonts in a different place other than app/assets/fonts. I have tried several solutions but after I found non-stupid-digest-assets gem, it just made it so easy.

Add this gem by adding the following line to your Gemfile:

gem 'non-stupid-digest-assets'

Then run:

bundle install

And finally add the following line in your config/initializers/non_digest_assets.rb file:

NonStupidDigestAssets.whitelist = [ /\.(?:svg|eot|woff|ttf)$/ ]

That's it. This solved my problem nicely. Hope this helps someone who have encountered similar problem like me.

Rails.env vs RAILS_ENV

Strange behaviour while debugging my app: require "active_support/notifications" (rdb:1) p ENV['RAILS_ENV'] "test" (rdb:1) p Rails.env "development"

I would say that you should stick to one or another (and preferably Rails.env)

How to modify JsonNode in Java?

The @Sharon-Ben-Asher answer is ok.

But in my case, for an array i have to use:

((ArrayNode) jsonNode).add("value");

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Under Apache 2+ you can simply do as below (Using Linux Terminal):

sudo a2enmod rewrite && sudo service apache2 restart

or

sudo a2enmod rewrite && sudo /etc/init.d/apache2 restart

Get folder name of the file in Python

os.path.dirname is what you are looking for -

os.path.dirname(r"C:\folder1\folder2\filename.xml")

Make sure you prepend r to the string so that its considered as a raw string.

Demo -

In [46]: os.path.dirname(r"C:\folder1\folder2\filename.xml")
Out[46]: 'C:\\folder1\\folder2'

If you just want folder2 , you can use os.path.basename with the above, Example -

os.path.basename(os.path.dirname(r"C:\folder1\folder2\filename.xml"))

Demo -

In [48]: os.path.basename(os.path.dirname(r"C:\folder1\folder2\filename.xml"))
Out[48]: 'folder2'

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

Remove .php extension with .htaccess

If your url in PHP like http://yourdomain.com/demo.php than comes like http://yourdomain.com/demo

This is all you need:

create file .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteRule ^([^\.]+)$ $1.html [NC,L]
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Class is not abstract and does not override abstract method

If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

join on multiple columns

The other queries are all going base on any ONE of the conditions qualifying and it will return a record... if you want to make sure the BOTH columns of table A are matched, you'll have to do something like...

select 
      tA.Col1,
      tA.Col2,
      tB.Val
   from
      TableA tA
         join TableB tB
            on  ( tA.Col1 = tB.Col1 OR tA.Col1 = tB.Col2 )
            AND ( tA.Col2 = tB.Col1 OR tA.Col2 = tB.Col2 )

'Must Override a Superclass Method' Errors after importing a project into Eclipse

To resolve this issue, Go to your Project properties -> Java compiler -> Select compiler compliance level to 1.6-> Apply.

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

It seems like it exists a bug in jQuery reported here : http://bugs.jquery.com/ticket/13183 that breaks the Fancybox script.

Also check https://github.com/fancyapps/fancyBox/issues/485 for further reference.

As a workaround, rollback to jQuery v1.8.3 while either the jQuery bug is fixed or Fancybox is patched.


UPDATE (Jan 16, 2013): Fancybox v2.1.4 has been released and now it works fine with jQuery v1.9.0.

For fancybox v1.3.4- you still need to rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.


UPDATE (Jan 17, 2013): Workaround for users of Fancybox v1.3.4 :

Patch the fancybox js file to make it work with jQuery v1.9.0 as follow :

  1. Open the jquery.fancybox-1.3.4.js file (full version, not pack version) with a text/html editor.
  2. Find around the line 29 where it says :

    isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
    

    and replace it by (EDITED March 19, 2013: more accurate filter):

    isIE6 = navigator.userAgent.match(/msie [6]/i) && !window.XMLHttpRequest,
    

    UPDATE (March 19, 2013): Also replace $.browser.msie by navigator.userAgent.match(/msie [6]/i) around line 615 (and/or replace all $.browser.msie instances, if any), thanks joofow ... that's it!

Or download the already patched version from HERE (UPDATED March 19, 2013 ... thanks fairylee for pointing out the extra closing bracket)

NOTE: this is an unofficial patch and is unsupported by Fancybox's author, however it works as is. You may use it at your own risk ;)

Optionally, you may rather rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.

adb doesn't show nexus 5 device

For those trying to connect their android phone in adb with no luck and have tried every USB configuration (MTP, PTP, RNDIS). It is worthing noting that in my case with my Nexus 5X on Windows 7 I successfully connected the phone to adb only by choosing the Charging USB Configuration. With any other configuration (MTP, PTP, ...) it doesn't work.

USB Driver: Google USB Driver v11

ADB Version: Android Debug Bridge version 1.0.39

Stored procedure - return identity as output parameter or scalar

I prefer to return the identity value as an output parameter. The result of the SP should indicate whether it succeeded or not. A value of 0 indicates the SP successfully completed, a non-zero value indicates an error. Also, if you ever need to make a change and return an additional value from the SP you don't need to make any changes other than adding an additional output parameter.

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

How to get an array of specific "key" in multidimensional array without looping

PHP 5.5+

Starting PHP5.5+ you have array_column() available to you, which makes all of the below obsolete.

PHP 5.3+

$ids = array_map(function ($ar) {return $ar['id'];}, $users);

Solution by @phihag will work flawlessly in PHP starting from PHP 5.3.0, if you need support before that, you will need to copy that wp_list_pluck.

PHP < 5.3

Wordpress 3.1+

In Wordpress there is a function called wp_list_pluck If you're using Wordpress that solves your problem.

PHP < 5.3

If you're not using Wordpress, since the code is open source you can copy paste the code in your project (and rename the function to something you prefer, like array_pick). View source here

Write / add data in JSON file using Node.js

Above example is also correct, but i provide simple example:

var fs = require("fs");
var sampleObject = {
    name: 'pankaj',
    member: 'stack',
    type: {
        x: 11,
        y: 22
    }
};

fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
    if (err) {
        console.error(err);
        return;
    };
    console.log("File has been created");
});

Download File to server from URL

best solution

install aria2c in system &

 echo exec("aria2c \"$url\"")

Android custom Row Item for ListView

you can follow BaseAdapter and create your custome Xml file and bind it with you BaseAdpter and populate it with Listview see here need to change xml file as Require.

In Python, how do I determine if an object is iterable?

try:
  #treat object as iterable
except TypeError, e:
  #object is not actually iterable

Don't run checks to see if your duck really is a duck to see if it is iterable or not, treat it as if it was and complain if it wasn't.

Mark error in form using Bootstrap

Bootstrap V3:

Once i was searching for laravel features then i got to know this amazing form validation. Later on, i amended glyphicon icon features. Now, it looks great.

<div class="col-md-12">
<div class="form-group has-error has-feedback">
    <input id="enter email" name="email" type="text" placeholder="Enter email" class="form-control ">
    <span class="glyphicon glyphicon-remove form-control-feedback"></span>       
    <span class="help-block"><p>The Email field is required.</p></span>                                        
</div>
</div>
<div class="clearfix"></div>

<div class="col-md-6">
<div class="form-group has-error has-feedback">
    <input id="account_holder_name" name="name" type="text" placeholder="Name" class="form-control ">
    <span class="glyphicon glyphicon-remove form-control-feedback"></span>                                            
    <span class="help-block"><p>The Name field is required.</p></span>                                        
</div>
</div>
<div class="col-md-6">
<div class="form-group has-error has-feedback">
 <input id="check_np" name="check_no" type="text" placeholder="Check no" class="form-control ">
 <span class="glyphicon glyphicon-remove form-control-feedback"></span>
<span class="help-block"><p>The Check No. field is required.</p></span>                                       
</div>
</div>

This is what it looks like: enter image description here

Once i completed it i thought i should implement it in Codeigniter as well. So here is the Codeigniter-3 validation with Bootstrap:

Controller

function addData()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|max_length[128]');
if($this->form_validation->run() == FALSE)
{
//validation fails. Load your view.
$this->loadViews('Load your view','pass your data to view if any');
}
else
{  
 //validation pass. Your code here.
}
}

View

<div class="col-md-12">
<?php 
 $email_error = (form_error('email') ? 'has-error has-feedback' : '');
 if(!empty($email_error)){
 $emailData = '<span class="help-block">'.form_error('email').'</span>';
 $emailClass = $email_error;
 $emailIcon = '<span class="glyphicon glyphicon-remove form-control-feedback"></span>';
}
else{
    $emailClass = $emailIcon = $emailData = '';
 } 
 ?>
<div class="form-group <?= $emailClass ?>">
<input id="enter email" name="email" type="text" placeholder="Enter email" class="form-control ">
<?= $emailIcon ?>
<?= $emailData ?>
</div>
</div>

Output: enter image description here

How to clean old dependencies from maven repositories?

I came up with a utility and hosted on GitHub to clean old versions of libraries in the local Maven repository. The utility, on its default execution removes all older versions of artifacts leaving only the latest ones. Optionally, it can remove all snapshots, sources, javadocs, and also groups or artifacts can be forced / excluded in this process. This cross platform also supports date based removal based on last access / download dates.

https://github.com/techpavan/mvn-repo-cleaner

Open new popup window without address bars in firefox & IE

check this if it works it works fine for me

<script>
  var windowObjectReference;
  var strWindowFeatures = "menubar=no,location=no,resizable=no,scrollbars=no,status=yes,width=400,height=350";

     function openRequestedPopup() {
      windowObjectReference = window.open("http://www.flyingedge.in/", "CNN_WindowName", strWindowFeatures);
     }
</script>

How can I generate a list of consecutive numbers?

import numpy as np

myList = np.linspace(0, 100, 1000) #Generates 1000 numbers from 0 to 100 in equal intervals

Detect Safari browser

For the records, the safest way I've found is to implement the Safari part of the browser-detection code from this answer:

const isSafari = window['safari'] && safari.pushNotification &&
    safari.pushNotification.toString() === '[object SafariRemoteNotification]';

Of course, the best way of dealing with browser-specific issues is always to do feature-detection, if at all possible. Using a piece of code like the above one is, though, still better than agent string detection.

Is Google Play Store supported in avd emulators?

Easiest way: You should create a new emulator, before opening it for the first time follow these 3 easy steps:

1- go to C:\Users[user].android\avd[your virtual device folder] open "config.ini" with text editor like notepad

2- change

"PlayStore.enabled=false" to "PlayStore.enabled=true"

3- change

mage.sysdir.1 = system-images\android-30\google_apis\x86\

to

image.sysdir.1 = system-images\android-30\google_apis_playstore\x86\

What is a plain English explanation of "Big O" notation?

Big O is a means to represent the upper bounds of any function. We generally use it for expressing the upper bounds of a function that tells the running time of an Algorithm.

Ex : f(n) = 2(n^2) +3n be a function representing the running time of a hypothetical algorithm, Big-O notation essentially gives the upper limit for this function which is O(n^2)

This notation basically tells us that, for any input 'n' the running time won't be greater than the value expressed by Big-O notation.

Also, agree with all the above detailed answers. Hope this helps !!

How to delete all data from solr and hbase

The curl examples above all failed for me when I ran them from a cygwin terminal. There were errors like this when i ran the script example.

curl http://192.168.2.20:7773/solr/CORE1/update --data '<delete><query>*:*</query></delete>' -H 'Content-type:text/xml; charset=utf-8'
<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader"><int name="status">0</int><int name="QTime">1</int></lst>
</response>
<!-- 
     It looks like it deleted stuff, but it did not go away
     maybe because the committing call failed like so 
-->
curl http://192.168.1.2:7773/solr/CORE1/update --data-binary '' -H 'Content-type:text/xml; charset=utf-8'
<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader"><int name="status">400</int><int name="QTime">2</int></lst><lst name="error"><str name="msg">Unexpected EOF in prolog
 at [row,col {unknown-source}]: [1,0]</str><int name="code">400</int></lst>
</response>

I needed to use the delete in a loop on core names to wipe them all out in a project.

This query below worked for me in the Cygwin terminal script.

curl http://192.168.1.2:7773/hpi/CORE1/update?stream.body=<delete><query>*:*</query></delete>&commit=true
<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader"><int name="status">0</int><int name="QTime">1</int></lst>
</response>

This one line made the data go away and the change persisted.

Adding script tag to React/JSX

This answer explains the why behind this behavior.

Any approach to render the script tag doesn't work as expected:

  1. Using the script tag for external scripts
  2. Using dangerouslySetInnerHTML

Why

React DOM (the renderer for react on web) uses createElement calls to render JSX into DOM elements.

createElement uses the innerHTML DOM API to finally add these to the DOM (see code in React source). innerHTML does not execute script tag added as a security consideration. And this is the reason why in turn rendering script tags in React doesn't work as expected.

For how to use script tags in React check some other answers on this page.

How to set a value to a file input in HTML?

Define in html:

<input type="hidden" name="image" id="image"/>

In JS:

ajax.jsonRpc("/consulta/dni", 'call', {'document_number': document_number})
    .then(function (data) {
        if (data.error){
            ...;
        }
        else {
            $('#image').val(data.image);
        }
    })

After:

<input type="hidden" name="image" id="image" value="/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8U..."/>
<button type="submit">Submit</button>

jQuery get values of checked checkboxes into array

var idsArr = [];

$('#tableID').find('input[type=checkbox]:checked').each(function() {
    idsArr .push(this.value);
});

console.log(idsArr);

Maven build debug in Eclipse

The Run/Debug configuration you're using is meant to let you run Maven on your workspace as if from the command line without leaving Eclipse.

Assuming your tests are JUnit based you should be able to debug them by choosing a source folder containing tests with the right button and choose Debug as... -> JUnit tests.

plot with custom text for x axis points

This worked for me. Each month on X axis

str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

Prior to standardization there was ioctl(...FIONBIO...) and fcntl(...O_NDELAY...), but these behaved inconsistently between systems, and even within the same system. For example, it was common for FIONBIO to work on sockets and O_NDELAY to work on ttys, with a lot of inconsistency for things like pipes, fifos, and devices. And if you didn't know what kind of file descriptor you had, you'd have to set both to be sure. But in addition, a non-blocking read with no data available was also indicated inconsistently; depending on the OS and the type of file descriptor the read may return 0, or -1 with errno EAGAIN, or -1 with errno EWOULDBLOCK. Even today, setting FIONBIO or O_NDELAY on Solaris causes a read with no data to return 0 on a tty or pipe, or -1 with errno EAGAIN on a socket. However 0 is ambiguous since it is also returned for EOF.

POSIX addressed this with the introduction of O_NONBLOCK, which has standardized behavior across different systems and file descriptor types. Because existing systems usually want to avoid any changes to behavior which might break backward compatibility, POSIX defined a new flag rather than mandating specific behavior for one of the others. Some systems like Linux treat all 3 the same, and also define EAGAIN and EWOULDBLOCK to the same value, but systems wishing to maintain some other legacy behavior for backward compatibility can do so when the older mechanisms are used.

New programs should use fcntl(...O_NONBLOCK...), as standardized by POSIX.

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

Michael-O gave useful approach to solve the problem. Another way to solve this is by starting the server with Putty Console.

Apache Cordova - uninstall globally

Super late here and I still couldn't uninstall using sudo as the other answers suggest. What did it for me was checking where cordova was installed by running

which cordova

it will output something like this

/usr/local/bin/

then removing by

rm -rf /usr/local/bin/cordova

Get the current script file name

__FILE__ use examples based on localhost server results:

echo __FILE__;
// C:\LocalServer\www\templates\page.php

echo strrchr( __FILE__ , '\\' );
// \page.php

echo substr( strrchr( __FILE__ , '\\' ), 1);
// page.php

echo basename(__FILE__, '.php');
// page

Codeigniter how to create PDF

TCPDF is PHP class for generating pdf documents.Here we will learn TCPDF integration with CodeIgniter.we will use following step for TCPDF integration with CodeIgniter.

Step 1

To Download TCPDF Click Here.

Step 2

Unzip the above download inside application/libraries/tcpdf.

Step 3

Create a new file inside application/libraries/Pdf.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once dirname(__FILE__) . '/tcpdf/tcpdf.php';
class Pdf extends TCPDF
{ function __construct() { parent::__construct(); }
}
/*Author:Tutsway.com */
/* End of file Pdf.php */
/* Location: ./application/libraries/Pdf.php */

Step 4

Create Controller file inside application/controllers/pdfexample.php.

 <?php
    class pdfexample extends CI_Controller{ 
    function __construct()
    { parent::__construct(); } function index() {
    $this->load->library('Pdf');
    $pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetTitle('Pdf Example');
    $pdf->SetHeaderMargin(30);
    $pdf->SetTopMargin(20);
    $pdf->setFooterMargin(20);
    $pdf->SetAutoPageBreak(true);
    $pdf->SetAuthor('Author');
    $pdf->SetDisplayMode('real', 'default');
    $pdf->Write(5, 'CodeIgniter TCPDF Integration');
    $pdf->Output('pdfexample.pdf', 'I'); }
    }
    ?>

It is working for me. I have taken reference from http://www.tutsway.com/codeignitertcpdf.php

View contents of database file in Android Studio

After going through all the solutions i will suggest

Use Stethos
Lets see how Simple it is

Add following dependencies in build.gradle file

compile 'com.facebook.stetho:stetho:1.5.0'
compile 'com.facebook.stetho:stetho-js-rhino:1.4.2'

Then go to you mainActivity onCreate method add following line

Stetho.initializeWithDefaults(this);

this would require you to

import com.facebook.stetho.Stetho;

now while running app from android studio , Open Chrome and in address bar type
chrome://inspect/

in the resources tab >web SQL check the the database and table play with it in real time easily

When should I use a table variable vs temporary table in sql server?

I totally agree with Abacus (sorry - don't have enough points to comment).

Also, keep in mind it doesn't necessarily come down to how many records you have, but the size of your records.

For instance, have you considered the performance difference between 1,000 records with 50 columns each vs 100,000 records with only 5 columns each?

Lastly, maybe you're querying/storing more data than you need? Here's a good read on SQL optimization strategies. Limit the amount of data you're pulling, especially if you're not using it all (some SQL programmers do get lazy and just select everything even though they only use a tiny subset). Don't forget the SQL query analyzer may also become your best friend.

How to remove the arrows from input[type="number"] in Opera

Those arrows are part of the Shadow DOM, which are basically DOM elements on your page which are hidden from you. If you're new to the idea, a good introductory read can be found here.

For the most part, the Shadow DOM saves us time and is good. But there are instances, like this question, where you want to modify it.

You can modify these in Webkit now with the right selectors, but this is still in the early stages of development. The Shadow DOM itself has no unified selectors yet, so the webkit selectors are proprietary (and it isn't just a matter of appending -webkit, like in other cases).

Because of this, it seems likely that Opera just hasn't gotten around to adding this yet. Finding resources about Opera Shadow DOM modifications is tough, though. A few unreliable internet sources I've found all say or suggest that Opera doesn't currently support Shadow DOM manipulation.

I spent a bit of time looking through the Opera website to see if there'd be any mention of it, along with trying to find them in Dragonfly...neither search had any luck. Because of the silence on this issue, and the developing nature of the Shadow DOM + Shadow DOM manipulation, it seems to be a safe conclusion that you just can't do it in Opera, at least for now.

Getting Hour and Minute in PHP

print date('H:i');

You have to set the correct timezone in php.ini .

Look for these lines:

[Date]

; Defines the default timezone used by the date functions

;date.timezone =

It will be something like :

date.timezone ="Europe/Lisbon"

Don't forget to restart your webserver.

Eclipse/Maven error: "No compiler is provided in this environment"

I had a problem with Eclipse Neon where the workspace default did not actually change even though I added the correct location under Preferences->Java->Installed JREs. This was in a new workspace I created to work on a code branch; it was originally set to the JRE location rather than the JDK. Yet even after changing the preferences, I could build with the command line, yet building in Eclipse produced the no compiler error. Please see

Maven Package Compilation Error

for my answer on which Eclipse configuration file(s) had to be manually edited to make Eclipse recognize the correct workspace default. I still have no idea why the preferences setting did not carry through to the new workspace's configuration.

How to escape single quotes within single quoted strings

How to escape single quotes (') and double quotes (") with hex and octal chars

If using something like echo, I've had some really complicated and really weird and hard-to-escape (think: very nested) cases where the only thing I could get to work was using octal or hex codes!

Here are some examples:

1. Single quote example, where ' is escaped with hex \x27 or octal \047 (its corresponding ASCII code):

# 1. hex
$ echo -e "Let\x27s get coding!"
Let's get coding!

# 2. octal
$ echo -e "Let\047s get coding!"
Let's get coding!

2. Double quote example, where " is escaped with hex \x22 or octal \042 (its corresponding ASCII code).

Note: bash is nuts! Sometimes even the ! char has special meaning, and must either be removed from within the double quotes and then escaped "like this"\! or put entirely within single quotes 'like this!', rather than within double quotes.

# 1. hex; escape `!` by removing it from within the double quotes 
# and escaping it with `\!`
$ echo -e "She said, \x22Let\x27s get coding"\!"\x22"
She said, "Let's get coding!"

# OR put it all within single quotes:
$ echo -e 'She said, \x22Let\x27s get coding!\x22'
She said, "Let's get coding!"


# 2. octal; escape `!` by removing it from within the double quotes 
$ echo -e "She said, \042Let\047s get coding"\!"\042"
She said, "Let's get coding!"

# OR put it all within single quotes:
$ echo -e 'She said, \042Let\047s get coding!\042'
She said, "Let's get coding!"


# 3. mixed hex and octal, just for fun
# escape `!` by removing it from within the double quotes when it is followed by
# another escape sequence
$ echo -e "She said, \x22Let\047s get coding! It\x27s waaay past time to begin"\!"\042"
She said, "Let's get coding! It's waaay past time to begin!"

# OR put it all within single quotes:
$ echo -e 'She said, \x22Let\047s get coding! It\x27s waaay past time to begin!\042'
She said, "Let's get coding! It's waaay past time to begin!"

Note that if you don't properly escape !, when needed, as I've shown two ways to do above, you'll get some weird errors, like this:

$ echo -e "She said, \x22Let\047s get coding! It\x27s waaay past time to begin!\042"
bash: !\042: event not found

OR:

$ echo -e "She said, \x22Let\x27s get coding!\x22"
bash: !\x22: event not found

References:

  1. https://en.wikipedia.org/wiki/ASCII#Printable_characters
  2. https://serverfault.com/questions/208265/what-is-bash-event-not-found/208266#208266
  3. See also my other answer here: How do I write non-ASCII characters using echo?.

Getting a better understanding of callback functions in JavaScript

Callbacks are about signals and "new" is about creating object instances.

In this case it would be even more appropriate to execute just "callback();" than "return new callback()" because you aren't doing anything with a return value anyway.

(And the arguments.length==3 test is really clunky, fwiw, better to check that callback param exists and is a function.)

How do I disable right click on my web page?

Use this function to disable right click.You can disable left click and tap also by checking 1 and 0 corresponding

document.onmousedown = rightclickD;
            function rightclickD(e) 
            { 
                e = e||event;
                console.log(e);
                if (e.button == 2) {
                //alert('Right click disabled!!!'); 
                 return false; }
            }

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

The most important thing to remember:

The only way to get a constant, variable (any result) from TenorFlow is the session.

Knowing this everything else is easy:

Both tf.Session.run() and tf.Tensor.eval() get results from the session where tf.Tensor.eval() is a shortcut for calling tf.get_default_session().run(t)


I would also outline the method tf.Operation.run() as in here:

After the graph has been launched in a session, an Operation can be executed by passing it to tf.Session.run(). op.run() is a shortcut for calling tf.get_default_session().run(op).

How to Generate Unique Public and Private Key via RSA

The RSACryptoServiceProvider(CspParameters) constructor creates a keypair which is stored in the keystore on the local machine. If you already have a keypair with the specified name, it uses the existing keypair.

It sounds as if you are not interested in having the key stored on the machine.

So use the RSACryptoServiceProvider(Int32) constructor:

public static void AssignNewKey(){
    RSA rsa = new RSACryptoServiceProvider(2048); // Generate a new 2048 bit RSA key

    string publicPrivateKeyXML = rsa.ToXmlString(true);
    string publicOnlyKeyXML = rsa.ToXmlString(false);
    // do stuff with keys...
}

EDIT:

Alternatively try setting the PersistKeyInCsp to false:

public static void AssignNewKey(){
    const int PROVIDER_RSA_FULL = 1;
    const string CONTAINER_NAME = "KeyContainer";
    CspParameters cspParams;
    cspParams = new CspParameters(PROVIDER_RSA_FULL);
    cspParams.KeyContainerName = CONTAINER_NAME;
    cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
    cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
    rsa = new RSACryptoServiceProvider(cspParams);

    rsa.PersistKeyInCsp = false;

    string publicPrivateKeyXML = rsa.ToXmlString(true);
    string publicOnlyKeyXML = rsa.ToXmlString(false);
    // do stuff with keys...
}

Simple http post example in Objective-C?

ASIHTTPRequest makes network communication really easy

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:@"Ben" forKey:@"names"];
[request addPostValue:@"George" forKey:@"names"];
[request addFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photos"];
[request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg" forKey:@"photos"];

Read an Excel file directly from a R script

As noted above in many of the other answers, there are many good packages that connect to the XLS/X file and get the data in a reasonable way. However, you should be warned that under no circumstances should you use the clipboard (or a .csv) file to retrieve data from Excel. To see why, enter =1/3 into a cell in excel. Now, reduce the number of decimal points visible to you to two. Then copy and paste the data into R. Now save the CSV. You'll notice in both cases Excel has helpfully only kept the data that was visible to you through the interface and you've lost all of the precision in your actual source data.

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

From a new Ubuntu 16.04 Installation

1) Terminal => Edit => Profile Preferences

2) Command Tab => Check Run command as a login shell

3) Close, and reopen terminal

rvm --default use 2.2.4

JavaScript replace/regex

Your regex pattern should have the g modifier:

var pattern = /[somepattern]+/g;

notice the g at the end. it tells the replacer to do a global replace.

Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:

var pattern = /[0-9a-zA-Z]+/g;

a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.

EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):

var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");

But you would need to change your replace function to this:

this.markup = this.markup.replace(pattern, value);

How to fix libeay32.dll was not found error

Download libeay32.dll and ssleay32.dll binary package for 32Bit and 64Bit from http://indy.fulgan.com/SSL/ then put it into executable or System32 directory.

Useful example of a shutdown hook in Java?

You could do the following:

  • Let the shutdown hook set some AtomicBoolean (or volatile boolean) "keepRunning" to false
  • (Optionally, .interrupt the working threads if they wait for data in some blocking call)
  • Wait for the working threads (executing writeBatch in your case) to finish, by calling the Thread.join() method on the working threads.
  • Terminate the program

Some sketchy code:

  • Add a static volatile boolean keepRunning = true;
  • In run() you change to

    for (int i = 0; i < N && keepRunning; ++i)
        writeBatch(pw, i);
    
  • In main() you add:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            keepRunning = false;
            mainThread.join();
        }
    });
    

That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.


From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.

How to clean node_modules folder of packages that are not in package.json?

I have added few lines inside package.json:

"scripts": {
  ...
  "clean": "rmdir /s /q node_modules",
  "reinstall": "npm run clean && npm install",
  "rebuild": "npm run clean && npm install && rmdir /s /q dist && npm run build --prod",
  ...
}

If you want to clean only you can use this rimraf node_modules or rm -rf node_modules.

It works fine

Postgres FOR LOOP

Procedural elements like loops are not part of the SQL language and can only be used inside the body of a procedural language function, procedure (Postgres 11 or later) or a DO statement, where such additional elements are defined by the respective procedural language. The default is PL/pgSQL, but there are others.

Example with plpgsql:

DO
$do$
BEGIN 
   FOR i IN 1..25 LOOP
      INSERT INTO playtime.meta_random_sample
         (col_i, col_id)                       -- declare target columns!
      SELECT  i,     id
      FROM   tbl
      ORDER  BY random()
      LIMIT  15000;
   END LOOP;
END
$do$;

For many tasks that can be solved with a loop, there is a shorter and faster set-based solution around the corner. Pure SQL equivalent for your example:

INSERT INTO playtime.meta_random_sample (col_i, col_id)
SELECT t.*
FROM   generate_series(1,25) i
CROSS  JOIN LATERAL (
   SELECT i, id
   FROM   tbl
   ORDER  BY random()
   LIMIT  15000
   ) t;

About generate_series():

About optimizing performance of random selections:

ActionController::UnknownFormat

Well I fond this post because I got a similar error. So I added the top line like in your controller respond_to :html, :json

then I got a different error(see below)

The controller-level respond_to' feature has been extracted to theresponders` gem. Add it to your Gemfile to continue using this feature: gem 'responders', '~> 2.0' Consult the Rails upgrade guide for details. But that had nothing to do with it.

How to add an image to the emulator gallery in android studio?

After trying to add an image via the Device Monitor or via drop, I could find it when exploring, but it was still not shown in the Gallery.

For me, it helped to eject the (virtual) sdcard from Settings > Storage & USB and reinserting it.

In php, is 0 treated as empty?

empty() returns true for everything that evaluates to FALSE, it is actually a 'not' (!) in disguise. I think you meant isset()

How to force page refreshes or reloads in jQuery?

Replace with:

$('#something').click(function() {
    location.reload();
});

Linux c++ error: undefined reference to 'dlopen'

You needed to do something like this for the makefile:

LDFLAGS='-ldl'
make install

That'll pass the linker flags from make through to the linker. Doesn't matter that the makefile was autogenerated.

clearInterval() not working

The setInterval method returns an interval ID that you need to pass to clearInterval in order to clear the interval. You're passing a function, which won't work. Here's an example of a working setInterval/clearInterval

var interval_id = setInterval(myMethod,500);
clearInterval(interval_id);

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

You've got no SMTPSecure setting to define the type of authentication being used, and you're running the Host setting with the unnecessary 'ssl://' (PS -- ssl is over port 465, if you need to run it over ssl instead, see the accepted answer here. Here's the lines to add/change:

+ $mail->SMTPSecure = 'tls';

- $mail->Host = "ssl://smtp.gmail.com";
+ $mail->Host = "smtp.gmail.com";

How do you Programmatically Download a Webpage in Java

Here's some tested code using Java's URL class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though.

public static void main(String[] args) {
    URL url;
    InputStream is = null;
    BufferedReader br;
    String line;

    try {
        url = new URL("http://stackoverflow.com/");
        is = url.openStream();  // throws an IOException
        br = new BufferedReader(new InputStreamReader(is));

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (MalformedURLException mue) {
         mue.printStackTrace();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    } finally {
        try {
            if (is != null) is.close();
        } catch (IOException ioe) {
            // nothing to see here
        }
    }
}

(Deep) copying an array using jQuery

If you want to use pure JavaScript then try this:

 var arr=["apple","ball","cat","dog"];
 var narr=[];

 for(var i=0;i<arr.length;i++){
     narr.push(arr[i]);
 }
 alert(narr); //output: apple,ball,vat,dog
 narr.push("elephant");
 alert(arr); // output: apple,ball,vat,dog
 alert(narr); // apple,ball,vat,dog,elephant

Base64 encoding and decoding in oracle

All the previous posts are correct. There's more than one way to skin a cat. Here is another way to do the same thing: (just replace "what_ever_you_want_to_convert" with your string and run it in Oracle:

    set serveroutput on;
    DECLARE
    v_str VARCHAR2(1000);
    BEGIN
    --Create encoded value
    v_str := utl_encode.text_encode
    ('what_ever_you_want_to_convert','WE8ISO8859P1', UTL_ENCODE.BASE64);
    dbms_output.put_line(v_str);
    --Decode the value..
    v_str := utl_encode.text_decode
    (v_str,'WE8ISO8859P1', UTL_ENCODE.BASE64);
    dbms_output.put_line(v_str);
    END;
    /

source

Which is better: <script type="text/javascript">...</script> or <script>...</script>

Both will work but xhtml standard requires you to specify the type too:

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

<!ELEMENT SCRIPT - - %Script;          -- script statements -->
<!ATTLIST SCRIPT
  charset     %Charset;      #IMPLIED  -- char encoding of linked resource --
  type        %ContentType;  #REQUIRED -- content type of script language --
  src         %URI;          #IMPLIED  -- URI for an external script --
  defer       (defer)        #IMPLIED  -- UA may defer execution of script --
  >

type = content-type [CI] This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute.

Notices the emphasis above.

http://www.w3.org/TR/html4/interact/scripts.html

Note: As of HTML5 (far away), the type attribute is not required and is default.

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

You just need to manually set the desired permissions with chmod():

private function writeFileContent($file, $content){
    $fp = fopen($file, 'w');
    fwrite($fp, $content);
    fclose($fp);

    // Set perms with chmod()
    chmod($file, 0777);
    return true;
}