Programs & Examples On #Umount

umount detaches a specified file system from the file tree.

Unmount the directory which is mounted by sshfs in Mac

Try this:

umount -f <absolute pathname to the mount point>

Example:

umount -f /Users/plummie/Documents/stanford 

If that doesn't work, try the same command as root:

sudo umount -f ...

Linux: Which process is causing "device busy" when doing umount?

lsof +f -- /mountpoint

(as lists the processes using files on the mount mounted at /mountpoint. Particularly useful for finding which process(es) are using a mounted USB stick or CD/DVD.

Force unmount of NFS-mounted directory

I had the same problem, and neither umount /path -f, neither umount.nfs /path -f, neither fuser -km /path, works

finally I found a simple solution >.<

sudo /etc/init.d/nfs-common restart, then lets do the simple umount ;-)

How to unmount a busy device

Check for exported NFS file systems with exportfs -v. If found, remove with exportfs -d share:/directory. These don't show up in the fuser/lsof listing, and can prevent umount from succeeding.

Using stored procedure output parameters in C#

Stored Procedure.........

CREATE PROCEDURE usp_InsertContract
    @ContractNumber varchar(7)
AS
BEGIN

    INSERT into [dbo].[Contracts] (ContractNumber)
        VALUES (@ContractNumber)

    SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
END

C#

pvCommand.CommandType = CommandType.StoredProcedure;

pvCommand.Parameters.Clear();
pvCommand.Parameters.Add(new SqlParameter("@ContractNumber", contractNumber));
object uniqueId;
int id;
    try
    {
    uniqueId = pvCommand.ExecuteScalar();
     id = Convert.ToInt32(uniqueId);
    }
    catch (Exception e)
    {
        Debug.Print("  Message: {0}", e.Message);
    }
}

EDIT: "I still get back a DBNull value....Object cannot be cast from DBNull to other types. I'll take this up again tomorrow. I'm off to my other job,"

I believe the Id column in your SQL Table isn't a identity column.

enter image description here

conflicting types error when compiling c program using gcc

If you don't declare a function and it only appears after being called, it is automatically assumed to be int, so in your case, you didn't declare

void my_print (char *);
void my_print2 (char *);

before you call it in main, so the compiler assume there are functions which their prototypes are int my_print2 (char *); and int my_print2 (char *); and you can't have two functions with the same prototype except of the return type, so you get the error of conflicting types.

As Brian suggested, declare those two methods before main.

Python Set Comprehension

primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}

I simplified the test a bit - if all(x%y instead of if not any(not x%y

I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.

pairs = {(x, x+2) for x in primes if x+2 in primes}

Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.

Counting words in string

<textarea name="myMessage" onkeyup="wordcount(this.value)"></textarea>
<script type="text/javascript">
var cnt;
function wordcount(count) {
var words = count.split(/\s/);
cnt = words.length;
var ele = document.getElementById('w_count');
ele.value = cnt;
}
document.write("<input type=text id=w_count size=4 readonly>");
</script>

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

Error converting data types when importing from Excel to SQL Server 2008

A workaround to consider in a pinch:

  1. save a copy of the excel file, modify the column to format type 'text'
  2. copy the column values and paste to a text editor, save the file (call it tmp.txt).
  3. modify the data in the text file to start and end with a character so that the SQL Server import mechanism will recognize as text. If you have a fancy editor, use included tools. I use awk in cygwin on my windows laptop. For example, I start end end the column value with a single quote, like "$ awk '{print "\x27"$1"\x27"}' ./tmp.txt > ./tmp2.txt"
  4. copy and paste the data from tmp2.txt over top of the necessary column in the excel file, and save the excel file
  5. run the sql server import for your modified excel file... be sure to double check the data type chosen by the importer is not numeric... if it is, repeat the above steps with a different set of characters

The data in the database will have the quotes once the import is done... you can update the data later on to remove the quotes, or use the "replace" function in your read query, such as "replace([dbo].[MyTable].[MyColumn], '''', '')"

How to display an activity indicator with text on iOS 8 with Swift?

While Esq's answer works, I've added my own implementation which is more in line with good component architecture by separating the view into it's own class. It also uses dynamic blurring introduced in iOS 8.

Here is how mine looks with an image background:

enter image description here

The code for this is encapsulated in it's own UIView class which means you can reuse it whenever you desire.

Updated for Swift 3

Usage

func viewDidLoad() {
  super.viewDidLoad()

  // Create and add the view to the screen.
  let progressHUD = ProgressHUD(text: "Saving Photo")
  self.view.addSubview(progressHUD)
  // All done!

  self.view.backgroundColor = UIColor.black
}

UIView Code

import UIKit

class ProgressHUD: UIVisualEffectView {

  var text: String? {
    didSet {
      label.text = text
    }
  }

  let activityIndictor: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
  let label: UILabel = UILabel()
  let blurEffect = UIBlurEffect(style: .light)
  let vibrancyView: UIVisualEffectView

  init(text: String) {
    self.text = text
    self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
    super.init(effect: blurEffect)
    self.setup()
  }

  required init?(coder aDecoder: NSCoder) {
    self.text = ""
    self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
    super.init(coder: aDecoder)
    self.setup()
  }

  func setup() {
    contentView.addSubview(vibrancyView)
    contentView.addSubview(activityIndictor)
    contentView.addSubview(label)
    activityIndictor.startAnimating()
  }

  override func didMoveToSuperview() {
    super.didMoveToSuperview()

    if let superview = self.superview {

      let width = superview.frame.size.width / 2.3
      let height: CGFloat = 50.0
      self.frame = CGRect(x: superview.frame.size.width / 2 - width / 2,
                      y: superview.frame.height / 2 - height / 2,
                      width: width,
                      height: height)
      vibrancyView.frame = self.bounds

      let activityIndicatorSize: CGFloat = 40
      activityIndictor.frame = CGRect(x: 5,
                                      y: height / 2 - activityIndicatorSize / 2,
                                      width: activityIndicatorSize,
                                      height: activityIndicatorSize)

      layer.cornerRadius = 8.0
      layer.masksToBounds = true
      label.text = text
      label.textAlignment = NSTextAlignment.center
      label.frame = CGRect(x: activityIndicatorSize + 5,
                           y: 0,
                           width: width - activityIndicatorSize - 15,
                           height: height)
      label.textColor = UIColor.gray
      label.font = UIFont.boldSystemFont(ofSize: 16)
    }
  }

  func show() {
    self.isHidden = false
  }

  func hide() {
    self.isHidden = true
  }
}

Swift 2

An example on how to use it is like this:

override func viewDidLoad() {
    super.viewDidLoad()

    // Create and add the view to the screen.
    let progressHUD = ProgressHUD(text: "Saving Photo")
    self.view.addSubview(progressHUD)
    // All done!

    self.view.backgroundColor = UIColor.blackColor()
}

Here is the UIView code:

import UIKit

class ProgressHUD: UIVisualEffectView {

    var text: String? {
        didSet {
            label.text = text
        }
    }
    let activityIndictor: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
    let label: UILabel = UILabel()
    let blurEffect = UIBlurEffect(style: .Light)
    let vibrancyView: UIVisualEffectView

    init(text: String) {
        self.text = text
        self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
        super.init(effect: blurEffect)
        self.setup()
    }

    required init(coder aDecoder: NSCoder) {
        self.text = ""
        self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
        super.init(coder: aDecoder)
        self.setup()

    }

    func setup() {
        contentView.addSubview(vibrancyView)
        vibrancyView.contentView.addSubview(activityIndictor)
        vibrancyView.contentView.addSubview(label)
        activityIndictor.startAnimating()
    }

    override func didMoveToSuperview() {
        super.didMoveToSuperview()

        if let superview = self.superview {

            let width = superview.frame.size.width / 2.3
            let height: CGFloat = 50.0
            self.frame = CGRectMake(superview.frame.size.width / 2 - width / 2,
                superview.frame.height / 2 - height / 2,
                width,
                height)
            vibrancyView.frame = self.bounds

            let activityIndicatorSize: CGFloat = 40
            activityIndictor.frame = CGRectMake(5, height / 2 - activityIndicatorSize / 2,
                activityIndicatorSize,
                activityIndicatorSize)

            layer.cornerRadius = 8.0
            layer.masksToBounds = true
            label.text = text
            label.textAlignment = NSTextAlignment.Center
            label.frame = CGRectMake(activityIndicatorSize + 5, 0, width - activityIndicatorSize - 15, height)
            label.textColor = UIColor.grayColor()
            label.font = UIFont.boldSystemFontOfSize(16)
        }
    }

    func show() {
        self.hidden = false
    }

    func hide() {
        self.hidden = true
    }
}

I hope this helps, please feel free to use this code wherever you need.

bash assign default value

Please look at http://www.tldp.org/LDP/abs/html/parameter-substitution.html for examples

${parameter-default}, ${parameter:-default}

If parameter not set, use default. After the call, parameter is still not set.
Both forms are almost equivalent. The extra : makes a difference only when parameter has been declared, but is null.

unset EGGS
echo 1 ${EGGS-spam}   # 1 spam
echo 2 ${EGGS:-spam}  # 2 spam

EGGS=
echo 3 ${EGGS-spam}   # 3
echo 4 ${EGGS:-spam}  # 4 spam

EGGS=cheese
echo 5 ${EGGS-spam}   # 5 cheese
echo 6 ${EGGS:-spam}  # 6 cheese

${parameter=default}, ${parameter:=default}

If parameter not set, set parameter value to default.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null

# sets variable without needing to reassign
# colons suppress attempting to run the string
unset EGGS
: ${EGGS=spam}
echo 1 $EGGS     # 1 spam
unset EGGS
: ${EGGS:=spam}
echo 2 $EGGS     # 2 spam

EGGS=
: ${EGGS=spam}
echo 3 $EGGS     # 3        (set, but blank -> leaves alone)
EGGS=
: ${EGGS:=spam}
echo 4 $EGGS     # 4 spam

EGGS=cheese
: ${EGGS:=spam}
echo 5 $EGGS     # 5 cheese
EGGS=cheese
: ${EGGS=spam}
echo 6 $EGGS     # 6 cheese

${parameter+alt_value}, ${parameter:+alt_value}

If parameter set, use alt_value, else use null string. After the call, parameter value not changed.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null

unset EGGS
echo 1 ${EGGS+spam}  # 1
echo 2 ${EGGS:+spam} # 2

EGGS=
echo 3 ${EGGS+spam}  # 3 spam
echo 4 ${EGGS:+spam} # 4

EGGS=cheese
echo 5 ${EGGS+spam}  # 5 spam
echo 6 ${EGGS:+spam} # 6 spam

Convert String to equivalent Enum value

I might've over-engineered my own solution without realizing that Type.valueOf("enum string") actually existed.

I guess it gives more granular control but I'm not sure it's really necessary.

public enum Type {
    DEBIT,
    CREDIT;

    public static Map<String, Type> typeMapping = Maps.newHashMap();
    static {
        typeMapping.put(DEBIT.name(), DEBIT);
        typeMapping.put(CREDIT.name(), CREDIT);
    }

    public static Type getType(String typeName) {
        if (typeMapping.get(typeName) == null) {
            throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
        }
        return typeMapping.get(typeName);
    }
}

I guess you're exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code.

C++ performance vs. Java/C#

You should define "perform better than..". Well, I know, you asked about speed, but its not everything that counts.

  • Do virtual machines perform more runtime overhead? Yes!
  • Do they eat more working memory? Yes!
  • Do they have higher startup costs (runtime initialization and JIT compiler) ? Yes!
  • Do they require a huge library installed? Yes!

And so on, its biased, yes ;)

With C# and Java you pay a price for what you get (faster coding, automatic memory management, big library and so on). But you have not much room to haggle about the details: take the complete package or nothing.

Even if those languages can optimize some code to execute faster than compiled code, the whole approach is (IMHO) inefficient. Imagine driving every day 5 miles to your workplace, with a truck! Its comfortable, it feels good, you are safe (extreme crumple zone) and after you step on the gas for some time, it will even be as fast as a standard car! Why don't we all have a truck to drive to work? ;)

In C++ you get what you pay for, not more, not less.

Quoting Bjarne Stroustrup: "C++ is my favorite garbage collected language because it generates so little garbage" link text

Angular js init ng-model from default values

This one is a more generic version of the ideas mentioned above... It simply checks whether there is any value in the model, and if not, it sets the value to the model.

JS:

function defaultValueDirective() {
    return {
        restrict: 'A',
        controller: [
            '$scope', '$attrs', '$parse',
            function ($scope, $attrs, $parse) {
                var getter = $parse($attrs.ngModel);
                var setter = getter.assign;
                var value = getter();
                if (value === undefined || value === null) {
                    var defaultValueGetter = $parse($attrs.defaultValue);
                    setter($scope, defaultValueGetter());
                }
            }
        ]
    }
}

HTML (usage example):

<select class="form-control"
        ng-options="v for (i, v) in compressionMethods"
        ng-model="action.parameters.Method"
        default-value="'LZMA2'"></select>

MySQL check if a table exists without throwing an exception

$q = "SHOW TABLES";
$res = mysql_query($q, $con);
if ($res)
while ( $row = mysql_fetch_array($res, MYSQL_ASSOC) )
{
    foreach( $row as $key => $value )
    {
        if ( $value = BTABLE )  // BTABLE IS A DEFINED NAME OF TABLE
            echo "exist";
        else
            echo "not exist";
    }
}

In C#, can a class inherit from another class and an interface?

No, not exactly. But it can inherit from a class and implement one or more interfaces.

Clear terminology is important when discussing concepts like this. One of the things that you'll see mark out Jon Skeet's writing, for example, both here and in print, is that he is always precise in the way he decribes things.

How to call a method in another class in Java?

class A{
  public void methodA(){
    new B().methodB();
    //or
    B.methodB1();
  }
}

class B{
  //instance method
  public void methodB(){
  }
  //static method
  public static  void methodB1(){
  }
}

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

I got a similar prompt. It was because I had specified the x-axis in terms of some percentage (for example: 10%A, 20%B,....). So an alternate approach could be that you multiply these values and write them in the simplest form.

How to get a view table query (code) in SQL Server 2008 Management Studio

In Management Studio, open the Object Explorer.

  • Go to your database
  • There's a subnode Views
  • Find your view
  • Choose Script view as > Create To > New query window

and you're done!

enter image description here

If you want to retrieve the SQL statement that defines the view from T-SQL code, use this:

SELECT  
    m.definition    
FROM sys.views v
INNER JOIN sys.sql_modules m ON m.object_id = v.object_id
WHERE name = 'Example_1'

How to find the day, month and year with moment.js

Here's an example that you could use :

 var myDateVariable= moment("01/01/2019").format("dddd Do MMMM YYYY")
  • dddd : Full day Name

  • Do : day of the Month

  • MMMM : Full Month name

  • YYYY : 4 digits Year

For more informations :

https://flaviocopes.com/momentjs/

JQuery/Javascript: check if var exists

I suspect there are many answers like this on SO but here you go:

if ( typeof pagetype !== 'undefined' && pagetype == 'textpage' ) {
  ...
}

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

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

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

Convert a string into an int

See the NSString Class Reference.

NSString *string = @"5";
int value = [string intValue];

How do I get a list of all the duplicate items using pandas in python?

df[df.duplicated(['ID'])==True].sort_values('ID')

scp with port number specified

Copying file to host: scp SourceFile remoteuser@remotehost:/directory/TargetFile

Copying file from host: scp user@host:/directory/SourceFile TargetFile

Copying directory recursively from host: scp -r user@host:/directory/SourceFolder TargetFolder

NOTE: If the host is using a port other than port 22, you can specify it with the -P option: scp -P 2222 user@host:/directory/SourceFile TargetFile

How to convert an int to a hex string?

As an alternative representation you could use

[in] '%s' % hex(15)
[out]'0xf'

Insert new item in array on any position in PHP

You can try it, use this method to make it easy

/**
 * array insert element on position
 * 
 * @link https://vector.cool
 * 
 * @since 1.01.38
 *
 * @param array $original
 * @param mixed $inserted
 * @param int   $position
 * @return array
 */
function array_insert(&$original, $inserted, int $position): array
{
    array_splice($original, $position, 0, array($inserted));
    return $original;
}


$columns = [
    ['name' => '????', 'column' => 'item_name'],
    ['name' => '????', 'column' => 'start_time'],
    ['name' => '????', 'column' => 'full_name'],
    ['name' => '????', 'column' => 'phone'],
    ['name' => '????', 'column' => 'create_time']
];
$col = ['name' => '????', 'column' => 'user_id'];
$columns = array_insert($columns, $col, 3);
print_r($columns);

Print out:

Array
(
    [0] => Array
        (
            [name] => ????
            [column] => item_name
        )
    [1] => Array
        (
            [name] => ????
            [column] => start_time
        )
    [2] => Array
        (
            [name] => ????
            [column] => full_name
        )
    [3] => Array
        (
            [name] => ????1
            [column] => num_of_people
        )
    [4] => Array
        (
            [name] => ????
            [column] => phone
        )
    [5] => Array
        (
            [name] => ????
            [column] => user_id
        )
    [6] => Array
        (
            [name] => ????
            [column] => create_time
        )
)

JavaScript Extending Class

I can propose one variant, just have read in book, it seems the simplest:

function Parent() { 
  this.name = 'default name';
};

function Child() {
  this.address = '11 street';
};

Child.prototype = new Parent();      // child class inherits from Parent
Child.prototype.constructor = Child; // constructor alignment

var a = new Child(); 

console.log(a.name);                // "default name" trying to reach property of inherited class

How can I extract embedded fonts from a PDF as valid font files?

Eventually found the FontForge Windows installer package and opened the PDF through the installed program. Worked a treat, so happy.

Apply multiple functions to multiple groupby columns

Ted's answer is amazing. I ended up using a smaller version of that in case anyone is interested. Useful when you are looking for one aggregation that depends on values from multiple columns:

create a dataframe

df=pd.DataFrame({'a': [1,2,3,4,5,6], 'b': [1,1,0,1,1,0], 'c': ['x','x','y','y','z','z']})


   a  b  c
0  1  1  x
1  2  1  x
2  3  0  y
3  4  1  y
4  5  1  z
5  6  0  z

grouping and aggregating with apply (using multiple columns)

df.groupby('c').apply(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())

c
x    2.0
y    4.0
z    5.0

grouping and aggregating with aggregate (using multiple columns)

I like this approach since I can still use aggregate. Perhaps people will let me know why apply is needed for getting at multiple columns when doing aggregations on groups.

It seems obvious now, but as long as you don't select the column of interest directly after the groupby, you will have access to all the columns of the dataframe from within your aggregation function.

only access to the selected column

df.groupby('c')['a'].aggregate(lambda x: x[x>1].mean())

access to all columns since selection is after all the magic

df.groupby('c').aggregate(lambda x: x[(x['a']>1) & (x['b']==1)].mean())['a']

or similarly

df.groupby('c').aggregate(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())

I hope this helps.

jQuery each loop in table row

Just a recommendation:

I'd recommend using the DOM table implementation, it's very straight forward and easy to use, you really don't need jQuery for this task.

var table = document.getElementById('tblOne');

var rowLength = table.rows.length;

for(var i=0; i<rowLength; i+=1){
  var row = table.rows[i];

  //your code goes here, looping over every row.
  //cells are accessed as easy

  var cellLength = row.cells.length;
  for(var y=0; y<cellLength; y+=1){
    var cell = row.cells[y];

    //do something with every cell here
  }
}

How do you tell if caps lock is on using JavaScript?

In jQuery,

$('#example').keypress(function(e) { 
    var s = String.fromCharCode( e.which );
    if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
        alert('caps is on');
    }
});

Avoid the mistake, like the backspace key, s.toLowerCase() !== s is needed.

Read XML file using javascript

If you get this from a Webserver, check out jQuery. You can load it, using the Ajax load function and select the node or text you want, using Selectors.

If you don't want to do this in a http environment or avoid using jQuery, please explain in greater detail.

How to open mail app from Swift

Updated answer from Stephen Groom for Swift 3

let email = "[email protected]"
let url = URL(string: "mailto:\(email)")
UIApplication.shared.openURL(url!)

Why is NULL undeclared?

Are you including "stdlib.h" or "cstdlib" in this file? NULL is defined in stdlib.h/cstdlib

#include <stdlib.h>

or

#include <cstdlib>  // This is preferrable for c++

Dynamic loading of images in WPF

This is strange behavior and although I am unable to say why this is occurring, I can recommend some options.

First, an observation. If you include the image as Content in VS and copy it to the output directory, your code works. If the image is marked as None in VS and you copy it over, it doesn't work.

Solution 1: FileStream

The BitmapImage object accepts a UriSource or StreamSource as a parameter. Let's use StreamSource instead.

        FileStream stream = new FileStream("picture.png", FileMode.Open, FileAccess.Read);
        Image i = new Image();
        BitmapImage src = new BitmapImage();
        src.BeginInit();
        src.StreamSource = stream;
        src.EndInit();
        i.Source = src;
        i.Stretch = Stretch.Uniform;
        panel.Children.Add(i);

The problem: stream stays open. If you close it at the end of this method, the image will not show up. This means that the file stays write-locked on the system.

Solution 2: MemoryStream

This is basically solution 1 but you read the file into a memory stream and pass that memory stream as the argument.

        MemoryStream ms = new MemoryStream();
        FileStream stream = new FileStream("picture.png", FileMode.Open, FileAccess.Read);
        ms.SetLength(stream.Length);
        stream.Read(ms.GetBuffer(), 0, (int)stream.Length);

        ms.Flush();
        stream.Close();

        Image i = new Image();
        BitmapImage src = new BitmapImage();
        src.BeginInit();
        src.StreamSource = ms;
        src.EndInit();
        i.Source = src;
        i.Stretch = Stretch.Uniform;
        panel.Children.Add(i);

Now you are able to modify the file on the system, if that is something you require.

Javascript: How to pass a function with string parameters as a parameter to another function

Try this:

onclick="myfunction(
    '/myController/myAction',
    function(){myfuncionOnOK('/myController2/myAction2','myParameter2');},
    function(){myfuncionOnCancel('/myController3/myAction3','myParameter3');}
);"

Then you just need to call these two functions passed to myfunction:

function myfunction(url, f1, f2) {
    // …
    f1();
    f2();
}

How To Pass GET Parameters To Laravel From With GET Method ?

Router

Route::get('search/{id}', ['as' => 'search', 'uses' => 'SearchController@search']);

Controller

class SearchController extends BaseController {

    public function search(Request $request){

        $id= $request->id ; // or any params

        ...
    }
}

A variable modified inside a while loop is not remembered

Hmmm... I would almost swear that this worked for the original Bourne shell, but don't have access to a running copy just now to check.

There is, however, a very trivial workaround to the problem.

Change the first line of the script from:

#!/bin/bash

to

#!/bin/ksh

Et voila! A read at the end of a pipeline works just fine, assuming you have the Korn shell installed.

How to use in jQuery :not and hasClass() to get a specific element without a class

It's much easier to do like this:

if(!$('#foo').hasClass('bar')) { 
  ...
}

The ! in front of the criteria means false, works in most programming languages.

How to create a GUID in Excel?

As of modern version of Excel, there's the syntax with commas, not semicolons. I'm posting this answer for convenience of others so they don't have to replace the strings- We're all lazy... hrmp... human, right?

=CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,4294967295),8),DEC2HEX(RANDBETWEEN(0,42949),4))

Or, if you like me dislike when a guid screams and shouts and you, we can go lower-cased like this.

=LOWER(CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,4294967295),8),DEC2HEX(RANDBETWEEN(0,42949),4)))

How to exclude a directory from ant fileset, based on directories contents

You need to add a '/' after the dir name

<exclude name="WEB-INF/" />

Digital Certificate: How to import .cer file in to .truststore file using?

# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.

keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]

Trust this certificate: [Yes]

changeit is the default truststore password

How to bind Dataset to DataGridView in windows application

you can set the dataset to grid as follows:

//assuming your dataset object is ds

datagridview1.datasource= ds;
datagridview1.datamember= tablename.ToString();

tablename is the name of the table, which you want to show on the grid.

I hope, it helps.

B.R.

How to redirect to Login page when Session is expired in Java web application?

When the use logs in, put its username in the session:

`session.setAttribute("USER", username);`

At the beginning of each page you can do this:

<%
String username = (String)session.getAttribute("USER");
if(username==null) 
// if session is expired, forward it to login page
%>
<jsp:forward page="Login.jsp" />
<% { } %>

How can I add new keys to a dictionary?

If you want to add a dictionary within a dictionary you can do it this way.

Example: Add a new entry to your dictionary & sub dictionary

dictionary = {}
dictionary["new key"] = "some new entry" # add new dictionary entry
dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"}
print (dictionary)

Output:

{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}

NOTE: Python requires that you first add a sub

dictionary["dictionary_within_a_dictionary"] = {}

before adding entries.

Short form for Java if statement

You can write if, else if, else statements in short form. For example:

Boolean isCapital = city.isCapital(); //Object Boolean (not boolean)
String isCapitalName = isCapital == null ? "" : isCapital ? "Capital" : "City";      

This is short form of:

Boolean isCapital = city.isCapital();
String isCapitalName;
if(isCapital == null) {
    isCapitalName = "";
} else if(isCapital) {
    isCapitalName = "Capital";
} else {
    isCapitalName = "City";
}

Call to undefined function mysql_connect

Hi I got this error because I left out the ampersand (&) in

; php.ini
error_reporting = E_ALL & ~E_DEPRECATED

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

Adding class to element using Angular JS

try this code

<script>
       angular.element(document.querySelectorAll("#div1")).addClass("alpha");
</script>

click the link and understand more

Note: Keep in mind that angular.element() function will not find directly select any documnet location using this perameters angular.element(document).find(...) or $document.find(), or use the standard DOM APIs, e.g. document.querySelectorAll()

How to get HTML 5 input type="date" working in Firefox and/or IE 10

Here is the proper solution. You should use jquery datepicker everywhere

  <script>
  $( function() {
    $( ".simple_date" ).datepicker();
  } );
  </script>

Below is the link to get the complete code

https://tutorialvilla.com/how/how-to-solve-the-problem-of-html-date-picker

How do I go about adding an image into a java project with eclipse?

You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol

How to remove all callbacks from a Handler?

If you don't have the Runnable references, on the first callback, get the obj of the message, and use removeCallbacksAndMessages() to remove all related callbacks.

How to calculate difference between two dates in oracle 11g SQL

You can not use DATEDIFF but you can use this (if columns are not date type):

SELECT 
to_date('2008-08-05','YYYY-MM-DD')-to_date('2008-06-05','YYYY-MM-DD') 
AS DiffDate from dual

you can see the sample

http://sqlfiddle.com/#!4/d41d8/34609

git command to move a folder inside another

I solved this on windows by doing this:

  • Open Power shell console
  • run dir
  • Alt-click and drag over the file/folder name column, then copy
  • Paste to notepad++
  • run replace with regex: replace (.*) with git mv ".\\\1" ".\\<New_Folder_Here>\"
  • copy all text from notepad++ into powershell
  • hit enter

Apache and Node.js on the Same Server

You can use a different approach such as writing a reverse proxy server with nodejs to proxy both apache and all other nodejs apps.

First you need to make apache run on a different port other than port 80. ex: port 8080

Then you can write a reverse proxy script with nodejs as:

var proxy = require('redbird')({port: 80, xfwd: false);

proxy.register("mydomain.me/blog", "http://mydomain.me:8080/blog");
proxy.register("mydomain.me", "http://mydomain.me:3000");

Following article describes the whole process of making this.

RUN APACHE WITH NODE JS REVERSE PROXY – USING REDBIRD

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

How to create an Explorer-like folder browser control?

Take a look at Shell MegaPack control set. It provides Windows Explorer like folder/file browsing with most of the features and functionality like context menus, renaming, drag-drop, icons, overlay icons, thumbnails, etc

Convert List(of object) to List(of string)

No - if you want to convert ALL elements of a list, you'll have to touch ALL elements of that list one way or another.

You can specify / write the iteration in different ways (foreach()......, or .ConvertAll() or whatever), but in the end, one way or another, some code is going to iterate over each and every element and convert it.

Marc

Is a DIV inside a TD a bad idea?

Using a div instide a td is not worse than any other way of using tables for layout. (Some people never use tables for layout though, and I happen to be one of them.)

If you use a div in a td you will however get in a situation where it might be hard to predict how the elements will be sized. The default for a div is to determine its width from its parent, and the default for a table cell is to determine its size depending on the size of its content.

The rules for how a div should be sized is well defined in the standards, but the rules for how a td should be sized is not as well defined, so different browsers use slightly different algorithms.

Accidentally committed .idea directory files into git

Add .idea directory to the list of ignored files

First, add it to .gitignore, so it is not accidentally committed by you (or someone else) again:

.idea

Remove it from repository

Second, remove the directory only from the repository, but do not delete it locally. To achieve that, do what is listed here:

Remove a file from a Git repository without deleting it from the local filesystem

Send the change to others

Third, commit the .gitignore file and the removal of .idea from the repository. After that push it to the remote(s).

Summary

The full process would look like this:

$ echo '.idea' >> .gitignore
$ git rm -r --cached .idea
$ git add .gitignore
$ git commit -m '(some message stating you added .idea to ignored entries)'
$ git push

(optionally you can replace last line with git push some_remote, where some_remote is the name of the remote you want to push to)

Nesting queries in SQL

Query below should help you achieve what you want.

select scountry, headofstate from data 
where data.scountry like 'a%'and ttlppl>=100000

Regular expression to match DNS hostname or IP Address?

I think this is the best Ip validation regex. please check it once!!!

^(([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))\.){3}([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))$

How to change the integrated terminal in visual studio code or VSCode

Probably it is too late but the below thing worked for me:

  1. Open Settings --> this will open settings.json
  2. type terminal.integrated.windows.shell
  3. Click on {} at the top right corner -- this will open an editor where this setting can be over ridden.
  4. Set the value as terminal.integrated.windows.shell: C:\\Users\\<user_name>\\Softwares\\Git\\bin\\bash.exe
  5. Click Ctrl + S

Try to open new terminal. It should open in bash editor in integrated mode.

Get size of an Iterable in Java

If you are working with java 8 you may use:

Iterable values = ...
long size = values.spliterator().getExactSizeIfKnown();

it will only work if the iterable source has a determined size. Most Spliterators for Collections will, but you may have issues if it comes from a HashSetor ResultSetfor instance.

You can check the javadoc here.

If Java 8 is not an option, or if you don't know where the iterable comes from, you can use the same approach as guava:

  if (iterable instanceof Collection) {
        return ((Collection<?>) iterable).size();
    } else {
        int count = 0;
        Iterator iterator = iterable.iterator();
        while(iterator.hasNext()) {
            iterator.next();
            count++;
        }
        return count;
    }

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.

Time comparison

Adam explain well in his answer But I used this way. I think this is easiest way to understand time comparison in java

First create 3 calender object with set your time only , Hour and min.

then get GMT milliseconds of that time and simply compare.

Ex.

Calendar chechDateTime = Calendar.getInstance();
chechDateTime.set(Calendar.MILLISECOND, 0);
chechDateTime.set(Calendar.SECOND, 0);
chechDateTime.set(Calendar.HOUR, 11);
chechDateTime.set(Calendar.MINUTE, 22);


Calendar startDateTime = Calendar.getInstance();
startDateTime.set(Calendar.MILLISECOND, 0);
startDateTime.set(Calendar.SECOND, 0);
startDateTime.set(Calendar.HOUR, 10);
startDateTime.set(Calendar.MINUTE, 0);

Calendar endDateTime = Calendar.getInstance();
endDateTime.set(Calendar.MILLISECOND, 0);
endDateTime.set(Calendar.SECOND, 0);
endDateTime.set(Calendar.HOUR, 18);
endDateTime.set(Calendar.MINUTE, 22);

 long chechDateTimeMilliseconds=chechDateTime.getTime().getTime();
 long startDateTimeMilliseconds=startDateTime.getTime().getTime();
 long endDateTimeMilliseconds=endDateTime.getTime().getTime();


System.out.println("chechDateTime : "+chechDateTimeMilliseconds);
System.out.println("startDateTime "+startDateTimeMilliseconds);
System.out.println("endDateTime "+endDateTimeMilliseconds);



if(chechDateTimeMilliseconds>=startDateTimeMilliseconds && chechDateTimeMilliseconds <= endDateTimeMilliseconds ){
       System.out.println("In between ");
    }else{
         System.out.println("Not In between ");
    }

Output will look like this :

chechDateTime : 1397238720000
startDateTime 1397233800000
endDateTime 1397263920000
In between 

android button selector

You can use this code:

<Button
android:id="@+id/img_sublist_carat"
android:layout_width="70dp"
android:layout_height="68dp"
android:layout_centerVertical="true"
android:layout_marginLeft="625dp"
android:contentDescription=""
android:background="@drawable/img_sublist_carat_selector"
android:visibility="visible" />

(Selector File) img_sublist_carat_selector.xml:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_focused="true" 
       android:state_pressed="true"        
       android:drawable="@drawable/img_sublist_carat_highlight" />
 <item android:state_pressed="true" 
       android:drawable="@drawable/img_sublist_carat_highlight" />
 <item android:drawable="@drawable/img_sublist_carat_normal" />
</selector>

Why does git say "Pull is not possible because you have unmerged files"?

If you want to pull down a remote branch to run locally (say for reviewing or testing purposes), and when you $ git pull you get local merge conflicts:

$ git checkout REMOTE-BRANCH
$ git pull  (you get local merge conflicts)
$ git reset --hard HEAD (discards local conflicts, and resets to remote branch HEAD)
$ git pull (now get remote branch updates without local conflicts)

jQuery validation: change default error message

instead of these custom error messages we can specify the type of the text field.

Ex: set type of the field in to type = 'email'

then plugin will identify the field and validate correctly.

Unable to begin a distributed transaction

I was able to resolve this issue (as others mentioned in comments) by disabling "Enable Promotion of Distributed Transactions for RPC" (i.e. setting it to False):

enter image description here

As requested by @WonderWorker, you can do this via SQL script:

EXEC master.dbo.sp_serveroption
     @server = N'[mylinkedserver]',
     @optname = N'remote proc transaction promotion',
     @optvalue = N'false'

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

ProcessStartInfo hanging on "WaitForExit"? Why?

Mark Byers' answer is excellent, but I would just add the following:

The OutputDataReceived and ErrorDataReceived delegates need to be removed before the outputWaitHandle and errorWaitHandle get disposed. If the process continues to output data after the timeout has been exceeded and then terminates, the outputWaitHandle and errorWaitHandle variables will be accessed after being disposed.

(FYI I had to add this caveat as an answer as I couldn't comment on his post.)

Best way to parseDouble with comma as decimal separator?

Double.parseDouble(p.replace(',','.'))

...is very quick as it searches the underlying character array on a char-by-char basis. The string replace versions compile a RegEx to evaluate.

Basically replace(char,char) is about 10 times quicker and since you'll be doing these kind of things in low-level code it makes sense to think about this. The Hot Spot optimiser will not figure it out... Certainly doesn't on my system.

Android Lint contentDescription warning

Since I need the ImageView to add an icon just for aesthetics I've added tools:ignore="ContentDescription" within each ImageView I had in my xml file.

I'm no longer getting any error messages

Add target="_blank" in CSS

This is actually javascript but related/relevant because .querySelectorAll targets by CSS syntax:

var i_will_target_self = document.querySelectorAll("ul.menu li a#example")

this example uses css to target links in a menu with id = "example"

that creates a variable which is a collection of the elements we want to change, but we still have actually change them by setting the new target ("_blank"):

for (var i = 0; i < 5; i++) {
i_will_target_self[i].target = "_blank";
}

That code assumes that there are 5 or less elements. That can be changed easily by changing the phrase "i < 5."

read more here: http://xahlee.info/js/js_get_elements.html

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

Combine two data frames by rows (rbind) when they have different sets of columns

rbind.ordered=function(x,y){

  diffCol = setdiff(colnames(x),colnames(y))
  if (length(diffCol)>0){
    cols=colnames(y)
    for (i in 1:length(diffCol)) y=cbind(y,NA)
    colnames(y)=c(cols,diffCol)
  }

  diffCol = setdiff(colnames(y),colnames(x))
  if (length(diffCol)>0){
    cols=colnames(x)
    for (i in 1:length(diffCol)) x=cbind(x,NA)
    colnames(x)=c(cols,diffCol)
  }
  return(rbind(x, y[, colnames(x)]))
}

Enabling error display in PHP via htaccess only

This works for me (reference):

# PHP error handling for production servers
# Disable display of startup errors
php_flag display_startup_errors off

# Disable display of all other errors
php_flag display_errors off

# Disable HTML markup of errors
php_flag html_errors off

# Enable logging of errors
php_flag log_errors on

# Disable ignoring of repeat errors
php_flag ignore_repeated_errors off

# Disable ignoring of unique source errors
php_flag ignore_repeated_source off

# Enable logging of PHP memory leaks
php_flag report_memleaks on

# Preserve most recent error via php_errormsg
php_flag track_errors on

# Disable formatting of error reference links
php_value docref_root 0

# Disable formatting of error reference links
php_value docref_ext 0

# Specify path to PHP error log
php_value error_log /home/path/public_html/domain/PHP_errors.log

# Specify recording of all PHP errors
# [see footnote 3] # php_value error_reporting 999999999
php_value error_reporting -1

# Disable max error string length
php_value log_errors_max_len 0

# Protect error log by preventing public access
<Files PHP_errors.log>
 Order allow,deny
 Deny from all
 Satisfy All
</Files>

UTF-8 problems while reading CSV file with fgetcsv

In my case the source file has windows-1250 encoding and iconv prints tons of notices about illegal characters in input string...

So this solution helped me a lot:

/**
 * getting CSV array with UTF-8 encoding
 *
 * @param   resource    &$handle
 * @param   integer     $length
 * @param   string      $separator
 *
 * @return  array|false
 */
private function fgetcsvUTF8(&$handle, $length, $separator = ';')
{
    if (($buffer = fgets($handle, $length)) !== false)
    {
        $buffer = $this->autoUTF($buffer);
        return str_getcsv($buffer, $separator);
    }
    return false;
}

/**
 * automatic convertion windows-1250 and iso-8859-2 info utf-8 string
 *
 * @param   string  $s
 *
 * @return  string
 */
private function autoUTF($s)
{
    // detect UTF-8
    if (preg_match('#[\x80-\x{1FF}\x{2000}-\x{3FFF}]#u', $s))
        return $s;

    // detect WINDOWS-1250
    if (preg_match('#[\x7F-\x9F\xBC]#', $s))
        return iconv('WINDOWS-1250', 'UTF-8', $s);

    // assume ISO-8859-2
    return iconv('ISO-8859-2', 'UTF-8', $s);
}

Response to @manvel's answer - use str_getcsv instead of explode - because of cases like this:

some;nice;value;"and;here;comes;combinated;value";and;some;others

explode will explode string into parts:

some
nice
value
"and
here
comes
combinated
value"
and
some
others

but str_getcsv will explode string into parts:

some
nice
value
and;here;comes;combinated;value
and
some
others

How to write and save html file in python?

You can create multi-line strings by enclosing them in triple quotes. So you can store your HTML in a string and pass that string to write():

html_str = """
<table border=1>
     <tr>
       <th>Number</th>
       <th>Square</th>
     </tr>
     <indent>
     <% for i in range(10): %>
       <tr>
         <td><%= i %></td>
         <td><%= i**2 %></td>
       </tr>
     </indent>
</table>
"""

Html_file= open("filename","w")
Html_file.write(html_str)
Html_file.close()

Easy way to pull latest of all git submodules

From the top level in the repo:

git submodule foreach git checkout develop
git submodule foreach git pull

This will switch all branches to develop and pull latest

How to rebuild docker container in docker-compose.yml?

docker-compose stop nginx # stop if running
docker-compose rm -f nginx # remove without confirmation
docker-compose build nginx # build
docker-compose up -d nginx # create and start in background

Removing container with rm is essential. Without removing, Docker will start old container.

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Building on what is mentioned in the comments, the simplest solution would be:

@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {

    //whatever

}

class SomeDto {

   private List<WhateverBudgerPerDateDTO> budgetPerDate;


  //getters setters
}

The solution assumes that the HTTP request you are creating actually has

Content-Type:application/json instead of text/plain

What is Model in ModelAndView from Spring MVC?

Well, WelcomeMessage is just a variable name for message (actual model with data). Basically, you are binding the model with the welcomePage here. The Model (message) will be available in welcomePage.jsp as WelcomeMessage. Here is a simpler example:

ModelAndView("hello","myVar", "Hello World!");

In this case, my model is a simple string (In applications this will be a POJO with data fetched for DB or other sources.). I am assigning it to myVar and my view is hello.jsp. Now, myVar is available for me in hello.jsp and I can use it for display.

In the view, you can access the data though:

${myVar}

Similarly, You will be able to access the model through WelcomeMessage variable.

Get device token for push notification

NOTE: The below solution no longer works on iOS 13+ devices - it will return garbage data.

Please use following code instead:

+ (NSString *)hexadecimalStringFromData:(NSData *)data
{
  NSUInteger dataLength = data.length;
  if (dataLength == 0) {
    return nil;
  }

  const unsigned char *dataBuffer = (const unsigned char *)data.bytes;
  NSMutableString *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
  for (int i = 0; i < dataLength; ++i) {
    [hexString appendFormat:@"%02x", dataBuffer[i]];
  }
  return [hexString copy];
}

Solution that worked prior to iOS 13:

Objective-C

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 
{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"this will return '32 bytes' in iOS 13+ rather than the token", token);
} 

Swift 3.0

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print("this will return '32 bytes' in iOS 13+ rather than the token \(tokenString)")
}

ORA-28040: No matching authentication protocol exception

Adding

SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8

is the perfect solution sql.ora directory ..\product\12.1.0\dbhome_1\NETWORK\ADMIN

How can I commit files with git?

When you run git commit with no arguments, it will open your default editor to allow you to type a commit message. Saving the file and quitting the editor will make the commit.

It looks like your default editor is Vi or Vim. The reason "weird stuff" happens when you type is that Vi doesn't start in insert mode - you have to hit i on your keyboard first! If you don't want that, you can change it to something simpler, for example:

git config --global core.editor nano

Then you'll load the Nano editor (assuming it's installed!) when you commit, which is much more intuitive for users who've not used a modal editor such as Vi.

That text you see on your screen is just to remind you what you're about to commit. The lines are preceded by # which means they're comments, i.e. Git ignores those lines when you save your commit message. You don't need to type a message per file - just enter some text at the top of the editor's buffer.

To bypass the editor, you can provide a commit message as an argument, e.g.

git commit -m "Added foo to the bar"

How to extract public key using OpenSSL?

For those interested in the details - you can see what's inside the public key file (generated as explained above), by doing this:-

openssl rsa -noout -text -inform PEM -in key.pub -pubin

or for the private key file, this:-

openssl rsa -noout -text -in key.private

which outputs as text on the console the actual components of the key (modulus, exponents, primes, ...)

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

Similar issue with the PHP SDK, this works:

$s3Client = S3Client::factory(array('key'=>YOUR_AWS_KEY, 'secret'=>YOUR_AWS_SECRET, 'signature' => 'v4', 'region'=>'eu-central-1'));

The important bit is the signature and the region

Why is "except: pass" a bad programming practice?

The #1 reason has already been stated - it hides errors that you did not expect.

(#2) - It makes your code difficult for others to read and understand. If you catch a FileNotFoundException when you are trying to read a file, then it is pretty obvious to another developer what functionality the 'catch' block should have. If you do not specify an exception, then you need additional commenting to explain what the block should do.

(#3) - It demonstrates lazy programming. If you use the generic try/catch, it indicates either that you do not understand the possible run-time errors in your program, or that you do not know what exceptions are possible in Python. Catching a specific error shows that you understand both your program and the range of errors that Python throws. This is more likely to make other developers and code-reviewers trust your work.

"Bitmap too large to be uploaded into a texture"

Instead of spending hours upon hours trying to write/debug all this downsampling code manually, why not use Picasso? It was made for dealing with bitmaps of all types and/or sizes.

I have used this single line of code to remove my "bitmap too large...." problem:

Picasso.load(resourceId).fit().centerCrop().into(imageView);

How can I generate a list of files with their absolute path in Linux?

If you give find an absolute path to start with, it will print absolute paths. For instance, to find all .htaccess files in the current directory:

find "$(pwd)" -name .htaccess

or if your shell expands $PWD to the current directory:

find "$PWD" -name .htaccess

find simply prepends the path it was given to a relative path to the file from that path.

Greg Hewgill also suggested using pwd -P if you want to resolve symlinks in your current directory.

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

How do I code my submit button go to an email address

You might use Form tag with action attribute to submit the mailto.

Here is an example:

<form method="post" action="mailto:[email protected]" >
<input type="submit" value="Send Email" /> 
</form>

Can you run GUI applications in a Docker container?

The other solutions should work, but here is a solution for docker-compose.

To fix that error, you need to pass $DISPLAY and .X11-unix to docker, as well as grant the user who started docker access to xhost.

Within docker-compose.yml file:

version: '2'
services:
    node:
        build: .
        container_name: node
        environment:
            - DISPLAY
        volumes:
            - /tmp/.X11-unix:/tmp/.X11-unix

In terminal or script:

  • xhost +si:localuser:$USER
  • xhost +local:docker
  • export DISPLAY=$DISPLAY
  • docker-compose up

How can I start PostgreSQL server on Mac OS X?

This worked for me (macOS v10.13 (High Sierra)):

sudo -u postgres /Library/PostgreSQL/9.6/bin/pg_ctl start -D /Library/PostgreSQL/9.6/data

Or first

cd /Library/PostgreSQL/9.6/bin/

Bootstrap: Position of dropdown menu relative to navbar item

Even if it s late i hope i can help someone. if dropdown menu or submenu is on the right side of screen it's open on the left side, if menu or submenu is on the left it's open on the right side.

$(".dropdown-toggle").on("click", function(event){//"show.bs.dropdown"
    var liparent=$(this.parentElement);
    var ulChild=liparent.find('ul');
    var xOffset=liparent.offset().left;
    var alignRight=($(document).width()-xOffset)<xOffset;


    if (liparent.hasClass("dropdown-submenu"))
    {
        ulChild.css("left",alignRight?"-101%":"");
    }
    else
    {                
        ulChild.toggleClass("dropdown-menu-right",alignRight);
    }

});

To detect vertical position you can also add

$( document ).ready(function() {
        var liparent=$(".dropdown");
    var yOffset=liparent.offset().top;
        var toTop=($(document).height()-yOffset)<yOffset;
    liparent.toggleClass("dropup",toTop);
});

https://jsfiddle.net/jd1100/rf9zvdhg/28/

How do I use LINQ Contains(string[]) instead of Contains(string)

This is an example of one way of writing an extension method (note: I wouldn't use this for very large arrays; another data structure would be more appropriate...):

namespace StringExtensionMethods
{
    public static class StringExtension
    {
        public static bool Contains(this string[] stringarray, string pat)
        {
            bool result = false;

            foreach (string s in stringarray)
            {
                if (s == pat)
                {
                    result = true;
                    break;
                }
            }

            return result;
        }
    }
}

How to test an Internet connection with bash?

make sure your network allow TCP traffic in and out, then you could get back your public facing IP with the following command

curl ifconfig.co

How to validate white spaces/empty spaces? [Angular 2]

If you are using Angular Reactive Forms you can create a file with a function - a validator. This will not allow only spaces to be entered.

import { AbstractControl } from '@angular/forms';
export function removeSpaces(control: AbstractControl) {
  if (control && control.value && !control.value.replace(/\s/g, '').length) {
    control.setValue('');
  }
  return null;
}

and then in your component typescript file use the validator like this for example.

this.formGroup = this.fb.group({
  name: [null, [Validators.required, removeSpaces]]
});

Spring JSON request getting 406 (not Acceptable)

406 Not Acceptable

The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

So, your request accept header is application/json and your controller is not able to return that. This happens when the correct HTTPMessageConverter can not be found to satisfy the @ResponseBody annotated return value. HTTPMessageConverter are automatically registered when you use the <mvc:annotation-driven>, given certain 3-d party libraries in the classpath.

Either you don't have the correct Jackson library in your classpath, or you haven't used the <mvc:annotation-driven> directive.

I successfully replicated your scenario and it worked fine using these two libraries and no headers="Accept=*/*" directive.

  • jackson-core-asl-1.7.4.jar
  • jackson-mapper-asl-1.7.4.jar

sqlite database default time value 'now'

It is syntax error because you did not write parenthesis

if you write

Select datetime('now') then it will give you utc time but if you this write it query then you must add parenthesis before this so (datetime('now')) for UTC Time. for local time same Select datetime('now','localtime') for query

(datetime('now','localtime'))

how to compare two elements in jquery

The collection results you get back from a jQuery collection do not support set-based comparison. You can use compare the individual members one by one though, there are no utilities for this that I know of in jQuery.

NSString property: copy or retain?

For attributes whose type is an immutable value class that conforms to the NSCopying protocol, you almost always should specify copy in your @property declaration. Specifying retain is something you almost never want in such a situation.

Here's why you want to do that:

NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];

Person *p = [[[Person alloc] init] autorelease];
p.name = someName;

[someName setString:@"Debajit"];

The current value of the Person.name property will be different depending on whether the property is declared retain or copy — it will be @"Debajit" if the property is marked retain, but @"Chris" if the property is marked copy.

Since in almost all cases you want to prevent mutating an object's attributes behind its back, you should mark the properties representing them copy. (And if you write the setter yourself instead of using @synthesize you should remember to actually use copy instead of retain in it.)

$_SERVER['HTTP_REFERER'] missing

You can and should never assume that $_SERVER['HTTP_REFERER'] will be present.

If you control the previous page, you can pass the URL as a parameter "site.com/page2.php?prevUrl=".urlencode("site.com/page1.php").

If you don't control the page, then there is nothing you can do.

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

ValueError: Wrong number of items passed - Meaning and suggestions?

Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.

Copy a variable's value into another

Most of the answers here are using built-in methods or using libraries/frameworks. This simple method should work fine:

function copy(x) {
    return JSON.parse( JSON.stringify(x) );
}

// Usage
var a = 'some';
var b = copy(a);
a += 'thing';

console.log(b); // "some"

var c = { x: 1 };
var d = copy(c);
c.x = 2;

console.log(d); // { x: 1 }

CURL to pass SSL certifcate and password

Addition to previous answer make sure that your curl installation supports https.
You can use curl --version to get information about supported protocols.

If your curl supports https follow the previous answer.

curl --cert certificate_path:password https://www.example.com

If it does not support https, you need to install a cURL version that supports https.

What are some reasons for jquery .focus() not working?

Try something like this when you are applying focus that way if the element is hidden, it won't throw an error:

$("#elementid").filter(':visible').focus();

It may make more sense to make the element visible, though that will require code specific to your layout.

Read XML Attribute using XmlDocument

XmlNodeList elemList = doc.GetElementsByTagName(...);
for (int i = 0; i < elemList.Count; i++)
{
    string attrVal = elemList[i].Attributes["SuperString"].Value;
}

Using jQuery to build table rows from AJAX response(json)

Here is a complete answer from hmkcode.com

If we have such JSON data

// JSON Data
var articles = [
    { 
        "title":"Title 1",
        "url":"URL 1",
        "categories":["jQuery"],
        "tags":["jquery","json","$.each"]
    },
    {
        "title":"Title 2",
        "url":"URL 2",
        "categories":["Java"],
        "tags":["java","json","jquery"]
    }
];

And we want to view in this Table structure

<table id="added-articles" class="table">
            <tr>
                <th>Title</th>
                <th>Categories</th>
                <th>Tags</th>
            </tr>
        </table>

The following JS code will fill create a row for each JSON element

// 1. remove all existing rows
$("tr:has(td)").remove();

// 2. get each article
$.each(articles, function (index, article) {

    // 2.2 Create table column for categories
    var td_categories = $("<td/>");

    // 2.3 get each category of this article
    $.each(article.categories, function (i, category) {
        var span = $("<span/>");
        span.text(category);
        td_categories.append(span);
    });

    // 2.4 Create table column for tags
   var td_tags = $("<td/>");

    // 2.5 get each tag of this article    
    $.each(article.tags, function (i, tag) {
        var span = $("<span/>");
        span.text(tag);
        td_tags.append(span);
    });

    // 2.6 Create a new row and append 3 columns (title+url, categories, tags)
    $("#added-articles").append($('<tr/>')
            .append($('<td/>').html("<a href='"+article.url+"'>"+article.title+"</a>"))
            .append(td_categories)
            .append(td_tags)
    ); 
});  

Change multiple files

I'm surprised nobody has mentioned the -exec argument to find, which is intended for this type of use-case, although it will start a process for each matching file name:

find . -type f -name 'xa*' -exec sed -i 's/asd/dsg/g' {} \;

Alternatively, one could use xargs, which will invoke fewer processes:

find . -type f -name 'xa*' | xargs sed -i 's/asd/dsg/g'

Or more simply use the + exec variant instead of ; in find to allow find to provide more than one file per subprocess call:

find . -type f -name 'xa*' -exec sed -i 's/asd/dsg/g' {} +

How to find the extension of a file in C#?

You can check .flv signature. You can download specification here:

http://www.adobe.com/devnet/flv/

See "The FLV header" chapter.

How to ignore ansible SSH authenticity checking?

If you don't want to modify ansible.cfg or the playbook.yml then you can just set an environment variable:

export ANSIBLE_HOST_KEY_CHECKING=False

WPF: Grid with column/row margin/padding?

Edited:

To give margin to any control you could wrap the control with border like this

<!--...-->
    <Border Padding="10">
            <AnyControl>
<!--...-->

Difference between single and double quotes in Bash

Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \ escapes, etc.

Example:

$ echo "$(echo "upg")"
upg
$ echo '$(echo "upg")'
$(echo "upg")

The Bash manual has this to say:

3.1.2.2 Single Quotes

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

3.1.2.3 Double Quotes

Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.

The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

POST data to a URL in PHP

If you're looking to post data to a URL from PHP code itself (without using an html form) it can be done with curl. It will look like this:

$url = 'http://www.someurl.com';
$myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2;

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

This will send the post variables to the specified url, and what the page returns will be in $response.

How do I use a custom Serializer with Jackson?

As mentioned, @JsonValue is a good way. But if you don't mind a custom serializer, there's no need to write one for Item but rather one for User -- if so, it'd be as simple as:

public void serialize(Item value, JsonGenerator jgen,
    SerializerProvider provider) throws IOException,
    JsonProcessingException {
  jgen.writeNumber(id);
}

Yet another possibility is to implement JsonSerializable, in which case no registration is needed.

As to error; that is weird -- you probably want to upgrade to a later version. But it is also safer to extend org.codehaus.jackson.map.ser.SerializerBase as it will have standard implementations of non-essential methods (i.e. everything but actual serialization call).

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

I had a similar problem, you may find that going to the top right corner of your page in Eclipse and click "Java EE" instead of "Java" will solve your problem. I had EE installed correctly like you, and this solved the issue for me. Hope I helped :)

How to get overall CPU usage (e.g. 57%) on Linux

EDITED: I noticed that in another user's reply %idle was field 12 instead of field 11. The awk has been updated to account for the %idle field being variable.

This should get you the desired output:

mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { print 100 - $field }'

If you want a simple integer rounding, you can use printf:

mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { printf("%d%%",100 - $field) }'

How to Run Terminal as Administrator on Mac Pro

You can run a command as admin using

sudo <command>

You can also switch to root and every command will be run as root

sudo su

Getting datarow values into a string?

You can get a columns value by doing this

 rows["ColumnName"]

You will also have to cast to the appropriate type.

 output += (string)rows["ColumnName"]

Add context path to Spring Boot application

We can set it in the application.properties as API_CONTEXT_ROOT=/therootpath

And we access it in the Java class as mentioned below

@Value("${API_CONTEXT_ROOT}")
private String contextRoot;

What is the best open-source java charting library? (other than jfreechart)

There is JChart which is all open source. I'm not sure exactly what you are graphing and how you are graphing it (servlets, swing, etc) so I would say just look at a couple different ones and see which works for you.

http://sourceforge.net/projects/jchart/

I've also used JGraph but I've only used their commercial version. They do offer an open source version however:

http://www.jgraph.com/jgraph.html

'ssh-keygen' is not recognized as an internal or external command

I think you can add the location of the file ssh-keygen.exe in the PATH environment variable. Follow the steps: Go to My Computer->Right click->Properties->Advanced System Settings->Click Environmental Variables. Now click PATH and then click EDIT. In the variable value field, go to the end and append ';C:\path\to\msysgit1.7.11\bin\ssh-keygen.exe' (without quotes)

How can I pass a list as a command-line argument with argparse?

Additionally to nargs, you might want to use choices if you know the list in advance:

>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')

iOS 7 - Failing to instantiate default view controller

Check Is Initial View Controller in the Attributes Inspector.

enter image description here

Show whitespace characters in Visual Studio Code

All Platforms (Windows/Linux/Mac):

It is under View -> Render Whitespace.

?? Sometimes the menu item shows that it is currently active but you can's see white spaces. You should uncheck and check again to make it work. It is a known bug


A note about the macOS ?

In the mac environment, you can search for any menu option under the Help menu, then it will open the exact menu path you are looking for. For example, searching for whitespace result in this:

Demo

Splitting string into multiple rows in Oracle

I had the same problem, and xmltable helped me:

SELECT id, trim(COLUMN_VALUE) text FROM t, xmltable(('"' || REPLACE(text, ',', '","') || '"'))

How to print struct variables in console?

fmt.Println("%+v", structure variable)

A better way to do this would be to create a global constant for the string "%+v" in a package called "commons"(maybe) and use it everywhere in your code

//In commons package
const STRUCTURE_DATA_FMT = "%+v"

//In your code everywhere
fmt.Println(commons.STRUCTURE_DATA_FMT, structure variable)

Wampserver icon not going green fully, mysql services not starting up?

Basically this happens when you have not installed pre required software installed on your machine while installing Wampserver you might have got error bellow error at the time of installation.

program can't start because msvcr120.dll is missing OR

program can't start because msvcr120.dll is missing

If you fixed those issue after the installation of wampserver then you might get stuck at this problem.

Then You can simply uninstall and install wamp server again

And If you have not install pre required dependency then first of all uninstall wampserver . And then install pre requirement first and then finally you can install Wampserver and it should work now.

you can download Pre-required applications from following link

For x64 Machines

microsoft visual c++ 2010 redistributable package (x64) https://www.microsoft.com/en-in/download/details.aspx?id=14632

Visual C++ Redistributable for Visual Studio 2012 Update 4 https://www.microsoft.com/en-in/download/details.aspx?id=30679

Visual C++ Redistributable Packages for Visual Studio 2013 https://www.microsoft.com/en-in/download/details.aspx?id=40784

Visual C++ Redistributable for Visual Studio 2015 https://www.microsoft.com/en-in/download/details.aspx?id=48145

For x86 Machines

Microsoft Visual C++ 2010 Redistributable Package (x86) https://www.microsoft.com/en-in/download/details.aspx?id=14632

Visual C++ Redistributable for Visual Studio 2012 Update 4 https://www.microsoft.com/en-in/download/details.aspx?id=30679

Visual C++ Redistributable Packages for Visual Studio 2013 https://www.microsoft.com/en-in/download/details.aspx?id=40784

Visual C++ Redistributable for Visual Studio 2015 https://www.microsoft.com/en-in/download/details.aspx?id=48145

Note:- Take backup of your project files before uninstall

How to download all files (but not HTML) from a website using wget?

wget -m -p -E -k -K -np http://site/path/

man page will tell you what those options do.

wget will only follow links, if there is no link to a file from the index page, then wget will not know about its existence, and hence not download it. ie. it helps if all files are linked to in web pages or in directory indexes.

PHP, getting variable from another php-file

You could also use a session for passing small bits of info. You will need to have session_start(); at the top of the PHP pages that use the session else the variables will not be accessable

page1.php

<?php

   session_start();
   $_SESSION['superhero'] = "batman";

?>
<a href="page2.php" title="">Go to the other page</a>

page2.php

<?php 

   session_start(); // this NEEDS TO BE AT THE TOP of the page before any output etc
   echo $_SESSION['superhero'];

?>

undefined reference to `std::ios_base::Init::Init()'

You can resolve this in several ways:

  • Use g++ in stead of gcc: g++ -g -o MatSim MatSim.cpp
  • Add -lstdc++: gcc -g -o MatSim MatSim.cpp -lstdc++
  • Replace <string.h> by <string>

This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.

Shell script to check if file exists

One approach:

(
  shopt -s nullglob
  files=(/home/edward/bank1/fiche/Test*)
  if [[ "${#files[@]}" -gt 0 ]] ; then
    echo found one
  else
    echo found none
  fi
)

Explanation:

  • shopt -s nullglob will cause /home/edward/bank1/fiche/Test* to expand to nothing if no file matches that pattern. (Without it, it will be left intact.)
  • ( ... ) sets up a subshell, preventing shopt -s nullglob from "escaping".
  • files=(/home/edward/bank1/fiche/Test*) puts the file-list in an array named files. (Note that this is within the subshell only; files will not be accessible after the subshell exits.)
  • "${#files[@]}" is the number of elements in this array.

Edited to address subsequent question ("What if i also need to check that these files have data in them and are not zero byte files"):

For this version, we need to use -s (as you did in your question), which also tests for the file's existence, so there's no point using shopt -s nullglob anymore: if no file matches the pattern, then -s on the pattern will be false. So, we can write:

(
  found_nonempty=''
  for file in /home/edward/bank1/fiche/Test* ; do
    if [[ -s "$file" ]] ; then
      found_nonempty=1
    fi
  done
  if [[ "$found_nonempty" ]] ; then
    echo found one
  else
    echo found none
  fi
)

(Here the ( ... ) is to prevent file and found_file from "escaping".)

Unsupported major.minor version 52.0 when rendering in Android Studio

For me the problem was that the version of gradle in build.gradle was not same as the actual gradle version I had installed.

dependencies { classpath('com.android.tools.build:grade:2.2.0') { force = true}

Check your installed gradle versions at /Contents/gradle/m2repository/com/android/tools/build/gradle/ and change the above build.gradle file with

classpath('com.android.tools.build:grade:1.5.1') or <>

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Using momentjs to convert date to epoch then back to date

http://momentjs.com/docs/#/displaying/unix-timestamp/

You get the number of unix seconds, not milliseconds!

You you need to multiply it with 1000 or using valueOf() and don't forget to use a formatter, since you are using a non ISO 8601 format. And if you forget to pass the formatter, the date will be parsed in the UTC timezone or as an invalid date.

moment("10/15/2014 9:00", "MM/DD/YYYY HH:mm").valueOf()

Flutter position stack widget in center

You can use the Positioned.fill with Align inside a Stack:

Stack(
  children: <Widget>[      
    Positioned.fill(
      child: Align(
        alignment: Alignment.centerRight,
        child: ....                
      ),
    ),
  ],
),

How can I select the first day of a month in SQL?

SELECT @myDate - DAY(@myDate) + 1

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

updating web.config with the following assembly binding resolved the issue 
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">     
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed"
                culture="neutral" />
        <bindingRedirect oldVersion="4.5.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

How do you find the current user in a Windows environment?

%USERNAME% will get you the username of the currently running process. Depending on how you are running your batch file, this is not necessarily the same as the name of the current user. For example, you might be running your batch file through a scheduled task, from a service, etc.

Here is a more sure way of getting the username of the currently logged on user by scraping the name of the user that started the explorer.exe task:

for /f "TOKENS=1,2,*" %%a in ('tasklist /FI "IMAGENAME eq explorer.exe" /FO LIST /V') do if /i "%%a %%b"=="User Name:" set _currdomain_user=%%c
for /f "TOKENS=1,2 DELIMS=\" %%a in ("%_currdomain_user%") do set _currdomain=%%a & set _curruser=%%b

Creation timestamp and last update timestamp with Hibernate and MySQL

As data type in JAVA I strongly recommend to use java.util.Date. I ran into pretty nasty timezone problems when using Calendar. See this Thread.

For setting the timestamps I would recommend using either an AOP approach or you could simply use Triggers on the table (actually this is the only thing that I ever find the use of triggers acceptable).

Recursive search and replace in text files on Mac and Linux

This is my workable one. on mac OS X 10.10.4

grep -e 'this' -rl . | xargs sed -i '' 's/this/that/g'

The above ones use find will change the files that do not contain the search text (add a new line at the file end), which is verbose.

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

I know its an old question and lots of answers are helpful but in my case, I faced with the same error unluckily the reason was different. (Spring boot version 2.0.5.RELEASE) If you are using

IntelliJ idea 2018.1.5 or above and you set JDK version as JDK 11

the same exception occurred. After updating the

JDK version as 8

the error is gone.

How to set up subdomains on IIS 7

As DotNetMensch said but you DO NOT need to add another site in IIS as this can also cause further problems and make things more complicated because you then have a website within a website so the file paths, masterpage paths and web.config paths may need changing. You just need to edit teh bindings of the existing site and add the new subdomain there.

So:

  1. Add sub-domain to DNS records. My host (RackSpace) uses a web portal to do this so you just log in and go to Network->Domains(DNS)->Actions->Create Zone, and enter your subdomain as mysubdomain.domain.com etc, leave the other settings as default

  2. Go to your domain in IIS, right-click->Edit Bindings->Add, and add your new subdomain leaving everything else the same e.g. mysubdomain.domain.com

You may need to wait 5-10 mins for the DNS records to update but that's all you need.

Bootstrap 4 img-circle class not working

It's now called rounded-circle as explained here in the BS4 docs

<img src="img/gallery2.JPG" class="rounded-circle">

Demo

How to execute a JavaScript function when I have its name as a string

This is working for me:

var command = "Add";
var tempFunction = new Function("Arg1","Arg2", "window." + command + "(Arg1,Arg2)");
tempFunction(x,y);

I hope this works.

How to convert numbers between hexadecimal and decimal

Hex to Decimal Conversion

Convert.ToInt32(number, 16);

Decimal to Hex Conversion

int.Parse(number, System.Globalization.NumberStyles.HexNumber)

For more details Check this article

WinForms DataGridView font size

I too experienced same problem in the DataGridView but figured out that the DefaultCell style was inheriting the font of the groupbox (Datagrid is placed in groupbox). So changing the font of the groupbox changed the DefaultCellStyle too.

Regards

How to find the files that are created in the last hour in unix

sudo find / -Bmin 60

From the man page:

-Bmin n

True if the difference between the time of a file's inode creation and the time find was started, rounded up to the next full minute, is n minutes.

Obviously, you may want to set up a bit differently, but this primary seems the best solution for searching for any file created in the last N minutes.

Removing cordova plugins from the project

v2.0.0 of cordova-check-plugins enables you to remove all plugins in a project:

$ npm install -g cordova-check-plugins
$ cordova-check-plugins --remove-all

It will attempt to use the Cordova CLI to remove each plugin, but if this fails it will force removal of the plugin from platforms/ and plugins/.

If you also want to remove from config.xml, use:

$ cordova-check-plugins --remove-all --save

Disclaimer: I am the author of cordova-check-plugins

Mocking member variables of a class using Mockito

Yes, this can be done, as the following test shows (written with the JMockit mocking API, which I develop):

@Test
public void testFirst(@Mocked final Second sec) {
    new NonStrictExpectations() {{ sec.doSecond(); result = "Stubbed Second"; }};

    First first = new First();
    assertEquals("Stubbed Second", first.doSecond());
}

With Mockito, however, such a test cannot be written. This is due to the way mocking is implemented in Mockito, where a subclass of the class to be mocked is created; only instances of this "mock" subclass can have mocked behavior, so you need to have the tested code use them instead of any other instance.

How to get memory usage at runtime using C++?

Old:

maxrss states the maximum available memory for the process. 0 means that no limit is put upon the process. What you probably want is unshared data usage ru_idrss.

New: It seems that the above does not actually work, as the kernel does not fill most of the values. What does work is to get the information from proc. Instead of parsing it oneself though, it is easier to use libproc (part of procps) as follows:

// getrusage.c
#include <stdio.h>
#include <proc/readproc.h>

int main() {
  struct proc_t usage;
  look_up_our_self(&usage);
  printf("usage: %lu\n", usage.vsize);
}

Compile with "gcc -o getrusage getrusage.c -lproc"

Redis command to get all available keys?

We should be using --scan --pattern with redis 2.8 and later.

You can try using this wrapper on top of redis-cli. https://github.com/VijayantSoni/redis-helper

Rotate camera in Three.js with mouse

This might serve as a good starting point for moving/rotating/zooming a camera with mouse/trackpad (in typescript):

class CameraControl {
    zoomMode: boolean = false
    press: boolean = false
    sensitivity: number = 0.02

    constructor(renderer: Three.Renderer, public camera: Three.PerspectiveCamera, updateCallback:() => void){
        renderer.domElement.addEventListener('mousemove', event => {
            if(!this.press){ return }

            if(event.button == 0){
                camera.position.y -= event.movementY * this.sensitivity
                camera.position.x -= event.movementX * this.sensitivity        
            } else if(event.button == 2){
                camera.quaternion.y -= event.movementX * this.sensitivity/10
                camera.quaternion.x -= event.movementY * this.sensitivity/10
            }

            updateCallback()
        })    

        renderer.domElement.addEventListener('mousedown', () => { this.press = true })
        renderer.domElement.addEventListener('mouseup', () => { this.press = false })
        renderer.domElement.addEventListener('mouseleave', () => { this.press = false })

        document.addEventListener('keydown', event => {
            if(event.key == 'Shift'){
                this.zoomMode = true
            }
        })

        document.addEventListener('keyup', event => {
            if(event.key == 'Shift'){
                this.zoomMode = false
            }
        })

        renderer.domElement.addEventListener('mousewheel', event => {
            if(this.zoomMode){ 
                camera.fov += event.wheelDelta * this.sensitivity
                camera.updateProjectionMatrix()
            } else {
                camera.position.z += event.wheelDelta * this.sensitivity
            }

            updateCallback()
        })
    }
}

drop it in like:

this.cameraControl = new CameraControl(renderer, camera, () => {
    // you might want to rerender on camera update if you are not rerendering all the time
    window.requestAnimationFrame(() => renderer.render(scene, camera))
})

Controls:

  • move while [holding mouse left / single finger on trackpad] to move camera in x/y plane
  • move [mouse wheel / two fingers on trackpad] to move up/down in z-direction
  • hold shift + [mouse wheel / two fingers on trackpad] to zoom in/out via increasing/decreasing field-of-view
  • move while holding [mouse right / two fingers on trackpad] to rotate the camera (quaternion)

Additionally:

If you want to kinda zoom by changing the 'distance' (along yz) instead of changing field-of-view you can bump up/down camera's position y and z while keeping the ratio of position's y and z unchanged like:

// in mousewheel event listener in zoom mode
const ratio = camera.position.y / camera.position.z
camera.position.y += (event.wheelDelta * this.sensitivity * ratio)
camera.position.z += (event.wheelDelta * this.sensitivity)

IE9 jQuery AJAX with CORS returns "Access is denied"

Building off the accepted answer by @dennisg, I accomplished this successfully using jQuery.XDomainRequest.js by MoonScript.

The following code worked correctly in Chrome, Firefox and IE10, but failed in IE9. I simply included the script and it now automagically works in IE9. (And probably 8, but I haven't tested it.)

var displayTweets = function () {
    $.ajax({
        cache: false,
        type: 'GET',
        crossDomain: true,
        url: Site.config().apiRoot + '/Api/GetTwitterFeed',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
            for (var tweet in data) {
                displayTweet(data[tweet]);
            }
        }
    });
};

How do I get HTTP Request body content in Laravel?

For those who are still getting blank response with $request->getContent(), you can use:

$request->all()

e.g:

public function foo(Request $request){
   $bodyContent = $request->all();
}

Which HTML Parser is the best?

Self plug: I have just released a new Java HTML parser: jsoup. I mention it here because I think it will do what you are after.

Its party trick is a CSS selector syntax to find elements, e.g.:

String html = "<html><head><title>First parse</title></head>"
  + "<body><p>Parsed HTML into a doc.</p></body></html>";
Document doc = Jsoup.parse(html);
Elements links = doc.select("a");
Element head = doc.select("head").first();

See the Selector javadoc for more info.

This is a new project, so any ideas for improvement are very welcome!

Preserve line breaks in angularjs

the css solution works, however you do not really get control on the styling. In my case I wanted a bit more space after the line break. Here is a directive I created to handle this (typescript):

function preDirective(): angular.IDirective {
    return {
        restrict: 'C',
        priority: 450,
        link: (scope, el, attr, ctrl) => {
            scope.$watch(
                () => el[0].innerHTML,
                (newVal) => {
                    let lineBreakIndex = newVal.indexOf('\n');
                    if (lineBreakIndex > -1 && lineBreakIndex !== newVal.length - 1 && newVal.substr(lineBreakIndex + 1, 4) != '</p>') {
                        let newHtml = `<p>${replaceAll(el[0].innerHTML, '\n\n', '\n').split('\n').join('</p><p>')}</p>`;
                        el[0].innerHTML = newHtml;
                    }
                }
            )
        }
    };

    function replaceAll(str, find, replace) {
        return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
    }

    function escapeRegExp(str) {
        return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }
}

angular.module('app').directive('pre', preDirective);

Use:

<div class="pre">{{item.description}}</div>

All it does is wraps each part of the text in to a <p> tag. After that you can style it however you want.

ORA-01882: timezone region not found

I was able to solve the same issue by setting the timezone in my linux system (Centos6.5).

Reposting from

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html

  1. set timezone in /etc/sysconfig/clock e.g. set to ZONE="America/Los_Angeles"

  2. sudo ln -sf /usr/share/zoneinfo/America/Phoenix /etc/localtime

To figure out the timezone value try to

ls /usr/share/zoneinfo

and look for the file that represents your timezone.

Once you've set these reboot the machine and try again.

How can I get an HTTP response body as a string?

Following is the code snippet which shows better way to handle the response body as a String whether it's a valid response or error response for the HTTP POST request:

BufferedReader reader = null;
OutputStream os = null;
String payload = "";
try {
    URL url1 = new URL("YOUR_URL");
    HttpURLConnection postConnection = (HttpURLConnection) url1.openConnection();
    postConnection.setRequestMethod("POST");
    postConnection.setRequestProperty("Content-Type", "application/json");
    postConnection.setDoOutput(true);
    os = postConnection.getOutputStream();
    os.write(eventContext.getMessage().getPayloadAsString().getBytes());
    os.flush();

    String line;
    try{
        reader = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
    }
    catch(IOException e){
        if(reader == null)
            reader = new BufferedReader(new InputStreamReader(postConnection.getErrorStream()));
    }
    while ((line = reader.readLine()) != null)
        payload += line.toString();
}       
catch (Exception ex) {
            log.error("Post request Failed with message: " + ex.getMessage(), ex);
} finally {
    try {
        reader.close();
        os.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return null;
    }
}

T-SQL get SELECTed value of stored procedure

there are three ways you can use: the RETURN value, and OUTPUT parameter and a result set

ALSO, watch out if you use the pattern: SELECT @Variable=column FROM table ...

if there are multiple rows returned from the query, your @Variable will only contain the value from the last row returned by the query.

RETURN VALUE
since your query returns an int field, at least based on how you named it. you can use this trick:

CREATE PROCEDURE GetMyInt
( @Param int)
AS
DECLARE @ReturnValue int

SELECT @ReturnValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN @ReturnValue
GO

and now call your procedure like:

DECLARE @SelectedValue int
       ,@Param         int
SET @Param=1
EXEC @SelectedValue = GetMyInt @Param
PRINT @SelectedValue

this will only work for INTs, because RETURN can only return a single int value and nulls are converted to a zero.

OUTPUT PARAMETER
you can use an output parameter:

CREATE PROCEDURE GetMyInt
( @Param     int
 ,@OutValue  int OUTPUT)
AS
SELECT @OutValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO

and now call your procedure like:

DECLARE @SelectedValue int
       ,@Param         int
SET @Param=1
EXEC GetMyInt @Param, @SelectedValue OUTPUT
PRINT @SelectedValue 

Output parameters can only return one value, but can be any data type

RESULT SET for a result set make the procedure like:

CREATE PROCEDURE GetMyInt
( @Param     int)
AS
SELECT MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO

use it like:

DECLARE @ResultSet table (SelectedValue int)
DECLARE @Param int
SET @Param=1
INSERT INTO @ResultSet (SelectedValue)
    EXEC GetMyInt @Param
SELECT * FROM @ResultSet 

result sets can have many rows and many columns of any data type

Best TCP port number range for internal applications

I decided to download the assigned port numbers from IANA, filter out the used ports, and sort each "Unassigned" range in order of most ports available, descending. This did not work, since the csv file has ranges marked as "Unassigned" that overlap other port number reservations. I manually expanded the ranges of assigned port numbers, leaving me with a list of all assigned port numbers. I then sorted that list and generated my own list of unassigned ranges.

Since this stackoverflow.com page ranked very high in my search about the topic, I figured I'd post the largest ranges here for anyone else who is interested. These are for both TCP and UDP where the number of ports in the range is at least 500.

Total   Start   End
829     29170   29998
815     38866   39680
710     41798   42507
681     43442   44122
661     46337   46997
643     35358   36000
609     36866   37474
596     38204   38799
592     33657   34248
571     30261   30831
563     41231   41793
542     21011   21552
528     28590   29117
521     14415   14935
510     26490   26999

Source (via the CSV download button):

http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml

How to detect online/offline event cross-browser?

you can detect offline cross-browser way easily like below

var randomValue = Math.floor((1 + Math.random()) * 0x10000)

$.ajax({
      type: "HEAD",
      url: "http://yoururl.com?rand=" + randomValue,
      contentType: "application/json",
      error: function(response) { return response.status == 0; },
      success: function() { return true; }
   });

you can replace yoururl.com by document.location.pathname.

The crux of the solution is, try to connect to your domain name, if you are not able to connect - you are offline. works cross browser.

How do I set the default value for an optional argument in Javascript?

ES6 Update - ES6 (ES2015 specification) allows for default parameters

The following will work just fine in an ES6 (ES015) environment...

function(nodeBox, str="hai")
{
  // ...
}

Editing hosts file to redirect url?

You could use the RedirectMatch directive in Apache to do something similar you want.

It's pretty simple.

RedirectMatch / http://222.222.222.222/

Anyway, I can't see any reason to do that thing. Aren't you trying to intercept traffic? There are better ways. For Linux boxes as a router: iptables -j REDIRECT + Squid or Apache. For Cisco routers, you can use WCCP to a Cache or Web Server...

Select tableview row programmatically

From reference documentation:

Calling this method does not cause the delegate to receive a tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath: message, nor does it send UITableViewSelectionDidChangeNotification notifications to observers.

What I would do is:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self doSomethingWithRowAtIndexPath:indexPath];
}

And then, from where you wanted to call selectRowAtIndexPath, you instead call doSomethingWithRowAtIndexPath. On top of that, you can additionally also call selectRowAtIndexPath if you want the UI feedback to happen.

How do I make an input field accept only letters in javaScript?

Try this:

var alphaExp = /^[a-zA-Z]+$/;
            if(document.myForm.name.match(alphaExp))
            {
                //Your logice will be here.
            }
            else{
                alert("Please enter only alphabets");
            }

Thanks.

Webpack "OTS parsing error" loading fonts

For me the problem was my regex expression. The below did the trick to get bootstrap working:

{
    test: /\.(woff|ttf|eot|svg)(\?v=[a-z0-9]\.[a-z0-9]\.[a-z0-9])?$/,
    loader: 'url-loader?limit=100000'
},

Difference between HashMap, LinkedHashMap and TreeMap

  • HashMap:

    • Order not maintains
    • Faster than LinkedHashMap
    • Used for store heap of objects
  • LinkedHashMap:

    • LinkedHashMap insertion order will be maintained
    • Slower than HashMap and faster than TreeMap
    • If you want to maintain an insertion order use this.
  • TreeMap:

    • TreeMap is a tree-based mapping
    • TreeMap will follow the natural ordering of key
    • Slower than HashMap and LinkedHashMap
    • Use TreeMap when you need to maintain natural(default) ordering

How can I pretty-print JSON using node.js?

I know this is old question. But maybe this can help you

JSON string

var jsonStr = '{ "bool": true, "number": 123, "string": "foo bar" }';

Pretty Print JSON

JSON.stringify(JSON.parse(jsonStr), null, 2);

Minify JSON

JSON.stringify(JSON.parse(jsonStr));

Import existing Gradle Git project into Eclipse

There is a simplest and quick way to import a Gradle project into Eclipse. Just download the Gradle plugin for Eclipse from here.
https://marketplace.eclipse.org/content/gradle-integration-eclipse-0

And then from import select Gradle and your project would be imported. Then you have to click on Build Model to run it.


EDIT
Above link for Gradle plugin is no more valid. You can use the link as mentioned in the comment by @vikramvi

https://marketplace.eclipse.org/content/buildship-gradle-integration

How to set image in circle in swift

If your image is rounded, it would have a height and width of the exact same size (i.e 120). You simply take half of that number and use that in your code (image.layer.cornerRadius = 60).

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

Tks Ramon Gil Moreno. Pasting in Terminal and then restarting R Studio did the trick:
write org.rstudio.RStudio force.LANG en_US.UTF-8

Environment: MAC OS High Sierra 10.13.1 // RStudio version 3.4.2 (2017-09-28) -- "Short Summer"

Ennio De Leon

How to use Git and Dropbox together?

I like the top-voted answer by Dan McNevin. I ended up doing the sequence of git commands too many times and decided to make a script. So here it is:

#!/bin/bash

# Usage
usage() {
    echo "Usage: ${0} -m [ master-branch-directory ] -r [ remote-branch-directory ] [ project-name ]"
    exit 1
}

# Defaults
defaults() {
    masterdir="${HOME}/Dropbox/git"
    remotedir="${PWD}"
    gitignorefile="# OS generated files #\n\n.DS_Store\n.DS_Store?\n.Spotlight-V100\n.Trashes\nehthumbs.db\nThumbs.db"
}

# Check if no arguments
if [ ${#} -eq 0 ] ; then
    echo "Error: No arguments specified"
    usage
fi

#Set defaults
defaults

# Parse arguments
while [ ${#} -ge 1 ]; do
    case "${1}" in
        '-h' | '--help' ) usage ;;
        '-m' )
            shift
            masterdir="${1}"
            ;;
        '-r' )
            shift
            remotedir="${1}"
            ;;
        * )
            projectname="${1##*/}"
            projectname="${projectname%.git}.git"
            ;;
    esac
    shift
done

# check if specified directories and project name exists
if [ -z "${projectname}" ]; then
    echo "Error: Project name not specified"
    usage
fi

if [ ! -d "${remotedir}" ]; then
    echo "Error: Remote directory ${remotedir} does not exist"
    usage
fi

if [ ! -d "${masterdir}" ]; then
    echo "Error: Master directory ${masterdir} does not exist"
    usage
fi

#absolute paths
remotedir="`( cd \"${remotedir}\" && pwd )`"
masterdir="`( cd \"${masterdir}\" && pwd )`"

#Make master git repository
cd "${masterdir}"
git init --bare "${projectname}"

#make local repository and push to master
cd "${remotedir}"
echo -e "${gitignorefile}" > .gitignore # default .gitignore file
git init
git add .
git commit -m "first commit"
git remote add origin "${masterdir}/${projectname}"
git push -u origin master

#done
echo "----- Locations -----"
echo "Remote branch location: ${remotedir}"
echo "Master branch location: ${masterdir}"
echo "Project Name: ${projectname}"

The script only requires a project name. It will generate a git repository in ~/Dropbox/git/ under the specified name and will push the entire contents of the current directory to the newly created origin master branch. If more than one project name is given, the right-most project name argument will be used.

Optionally, the -r command argument specifies the remote branch that will push to the origin master. The location of the project origin master can also be specified with the -m argument. A default .gitignore file is also placed in the remote branch directory. The directory and .gitignore file defaults are specified in the script.

Using wget to recursively fetch a directory with arbitrary files in it

All you need is two flags, one is "-r" for recursion and "--no-parent" (or -np) in order not to go in the '.' and ".." . Like this:

wget -r --no-parent http://example.com/configs/.vim/

That's it. It will download into the following local tree: ./example.com/configs/.vim . However if you do not want the first two directories, then use the additional flag --cut-dirs=2 as suggested in earlier replies:

wget -r --no-parent --cut-dirs=2 http://example.com/configs/.vim/

And it will download your file tree only into ./.vim/

In fact, I got the first line from this answer precisely from the wget manual, they have a very clean example towards the end of section 4.3.

Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++

Based on what @J. Calleja said, you have two choices

Method 1 - Random access

If you want to random access the element of Mat, just simply use

Mat.at<data_Type>(row_num, col_num) = value;

Method 2 - Continuous access

If you want to continuous access, OpenCV provides Mat iterator compatible with STL iterator and it's more C++ style

MatIterator_<double> it, end;
for( it = I.begin<double>(), end = I.end<double>(); it != end; ++it)
{
    //do something here
}

or

for(int row = 0; row < mat.rows; ++row) {
    float* p = mat.ptr(row); //pointer p points to the first place of each row
    for(int col = 0; col < mat.cols; ++col) {
         *p++;  // operation here
    }
}

If you have any difficulty to understand how Method 2 works, I borrow the picture from a blog post in the article Dynamic Two-dimensioned Arrays in C, which is much more intuitive and comprehensible.

See the picture below.

enter image description here

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Let's fit the model:

> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)

Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)

Residuals:
    Min      1Q  Median      3Q     Max 
-245.74 -113.99  -32.05  104.96  484.81 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 811.2267    76.9755  10.539 2.29e-13 ***
body.weight   7.0595     0.9776   7.221 7.03e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 
F-statistic: 52.15 on 1 and 42 DF,  p-value: 7.025e-09 

The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).

This can be computed using confint:

> confint(fit, 'body.weight', level=0.95)
               2.5 % 97.5 %
body.weight 5.086656 9.0324

Rearrange columns using cut

Using sed

Use sed with basic regular expression's nested subexpressions to capture and reorder the column content. This approach is best suited when there are a limited number of cuts to reorder columns, as in this case.

The basic idea is to surround interesting portions of the search pattern with \( and \), which can be played back in the replacement pattern with \# where # represents the sequential position of the subexpression in the search pattern.

For example:

$ echo "foo bar" | sed "s/\(foo\) \(bar\)/\2 \1/"

yields:

bar foo

Text outside a subexpression is scanned but not retained for playback in the replacement string.

Although the question did not discuss fixed width columns, we will discuss here as this is a worthy measure of any solution posed. For simplicity let's assume the file is space delimited although the solution can be extended for other delimiters.

Collapsing Spaces

To illustrate the simplest usage, let's assume that multiple spaces can be collapsed into single spaces, and the the second column values are terminated with EOL (and not space padded).

File:

bash-3.2$ cat f
Column1    Column2
str1       1
str2       2
str3       3
bash-3.2$ od -a f
0000000    C   o   l   u   m   n   1  sp  sp  sp  sp   C   o   l   u   m
0000020    n   2  nl   s   t   r   1  sp  sp  sp  sp  sp  sp  sp   1  nl
0000040    s   t   r   2  sp  sp  sp  sp  sp  sp  sp   2  nl   s   t   r
0000060    3  sp  sp  sp  sp  sp  sp  sp   3  nl 
0000072

Transform:

bash-3.2$ sed "s/\([^ ]*\)[ ]*\([^ ]*\)[ ]*/\2 \1/" f
Column2 Column1
1 str1
2 str2
3 str3
bash-3.2$ sed "s/\([^ ]*\)[ ]*\([^ ]*\)[ ]*/\2 \1/" f | od -a
0000000    C   o   l   u   m   n   2  sp   C   o   l   u   m   n   1  nl
0000020    1  sp   s   t   r   1  nl   2  sp   s   t   r   2  nl   3  sp
0000040    s   t   r   3  nl
0000045

Preserving Column Widths

Let's now extend the method to a file with constant width columns, while allowing columns to be of differing widths.

File:

bash-3.2$ cat f2
Column1    Column2
str1       1
str2       2
str3       3
bash-3.2$ od -a f2
0000000    C   o   l   u   m   n   1  sp  sp  sp  sp   C   o   l   u   m
0000020    n   2  nl   s   t   r   1  sp  sp  sp  sp  sp  sp  sp   1  sp
0000040   sp  sp  sp  sp  sp  nl   s   t   r   2  sp  sp  sp  sp  sp  sp
0000060   sp   2  sp  sp  sp  sp  sp  sp  nl   s   t   r   3  sp  sp  sp
0000100   sp  sp  sp  sp   3  sp  sp  sp  sp  sp  sp  nl
0000114

Transform:

bash-3.2$ sed "s/\([^ ]*\)\([ ]*\) \([^ ]*\)\([ ]*\)/\3\4 \1\2/" f2
Column2 Column1
1       str1      
2       str2      
3       str3      
bash-3.2$ sed "s/\([^ ]*\)\([ ]*\) \([^ ]*\)\([ ]*\)/\3\4 \1\2/" f2 | od -a
0000000    C   o   l   u   m   n   2  sp   C   o   l   u   m   n   1  sp
0000020   sp  sp  nl   1  sp  sp  sp  sp  sp  sp  sp   s   t   r   1  sp
0000040   sp  sp  sp  sp  sp  nl   2  sp  sp  sp  sp  sp  sp  sp   s   t
0000060    r   2  sp  sp  sp  sp  sp  sp  nl   3  sp  sp  sp  sp  sp  sp
0000100   sp   s   t   r   3  sp  sp  sp  sp  sp  sp  nl 
0000114

Lastly although the question's example does not have strings of unequal length, this sed expression support this case.

File:

bash-3.2$ cat f3
Column1    Column2
str1       1      
string2    2      
str3       3      

Transform:

bash-3.2$ sed "s/\([^ ]*\)\([ ]*\) \([^ ]*\)\([ ]*\)/\3\4 \1\2/" f3
Column2 Column1   
1       str1      
2       string2   
3       str3    
bash-3.2$ sed "s/\([^ ]*\)\([ ]*\) \([^ ]*\)\([ ]*\)/\3\4 \1\2/" f3 | od -a
0000000    C   o   l   u   m   n   2  sp   C   o   l   u   m   n   1  sp
0000020   sp  sp  nl   1  sp  sp  sp  sp  sp  sp  sp   s   t   r   1  sp
0000040   sp  sp  sp  sp  sp  nl   2  sp  sp  sp  sp  sp  sp  sp   s   t
0000060    r   i   n   g   2  sp  sp  sp  nl   3  sp  sp  sp  sp  sp  sp
0000100   sp   s   t   r   3  sp  sp  sp  sp  sp  sp  nl 
0000114

Comparison to other methods of column reordering under shell

  • Surprisingly for a file manipulation tool, awk is not well-suited for cutting from a field to end of record. In sed this can be accomplished using regular expressions, e.g. \(xxx.*$\) where xxx is the expression to match the column.

  • Using paste and cut subshells gets tricky when implementing inside shell scripts. Code that works from the commandline fails to parse when brought inside a shell script. At least this was my experience (which drove me to this approach).

Send inline image in email

We all have our preferred coding styles. This is what I did:

var pictures = new[]
{
    new { id = Guid.NewGuid(), type = "image/jpeg", tag = "justme", path = @"C:\Pictures\JustMe.jpg" },
    new { id = Guid.NewGuid(), type = "image/jpeg", tag = "justme-bw", path = @"C:\Pictures\JustMe-BW.jpg" }
}.ToList();

var content = $@"
<style type=""text/css"">
    body {{ font-family: Arial; font-size: 10pt; }}
</style>
<body>
<h4>{DateTime.Now:dddd, MMMM d, yyyy h:mm:ss tt}</h4>
<p>Some pictures</p>
<div>
    <p>Color Picture</p>
    <img src=cid:{{justme}} />
</div>
<div>
    <p>Black and White Picture</p>
    <img src=cid:{{justme-bw}} />
</div>
<div>
    <p>Color Picture repeated</p>
    <img src=cid:{{justme}} />
</div>
</body>
";

// Update content with picture guid
pictures.ForEach(p => content = content.Replace($"{{{p.tag}}}", $"{p.id}"));
// Create Alternate View
var view = AlternateView.CreateAlternateViewFromString(content, Encoding.UTF8, MediaTypeNames.Text.Html);
// Add the resources
pictures.ForEach(p => view.LinkedResources.Add(new LinkedResource(p.path, p.type) { ContentId = p.id.ToString() }));

using (var client = new SmtpClient()) // Set properties as needed or use config file
using (MailMessage message = new MailMessage()
{
    IsBodyHtml = true,
    BodyEncoding = Encoding.UTF8,
    Subject = "Picture Email",
    SubjectEncoding = Encoding.UTF8,
})
{
    message.AlternateViews.Add(view);
    message.From = new MailAddress("[email protected]");
    message.To.Add(new MailAddress("[email protected]"));
    client.Send(message);
}

What's the purpose of git-mv?

There's a niche case where git mv remains very useful: when you want to change the casing of a file name on a case-insensitive file system. Both APFS (mac) and NTFS (windows) are, by default, case-insensitive (but case-preserving).

greg.kindel mentions this in a comment on CB Bailey's answer.

Suppose you are working on a mac and have a file Mytest.txt managed by git. You want to change the file name to MyTest.txt.

You could try:

$ mv Mytest.txt MyTest.txt
overwrite MyTest.txt? (y/n [n]) y
$ git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

Oh dear. Git doesn't acknowledge there's been any change to the file.

You could work around this with by renaming the file completely then renaming it back:

$ mv Mytest.txt temp.txt
$ git rm Mytest.txt
rm 'Mytest.txt'
$ mv temp.txt MyTest.txt
$ git add MyTest.txt 
$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    renamed:    Mytest.txt -> MyTest.txt

Hurray!

Or you could save yourself all that bother by using git mv:

$ git mv Mytest.txt MyTest.txt
$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    renamed:    Mytest.txt -> MyTest.txt

jQuery Ajax POST example with PHP

To make an Ajax request using jQuery you can do this by the following code.

HTML:

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>

JavaScript:

Method 1

 /* Get from elements values */
 var values = $(this).serialize();

 $.ajax({
        url: "test.php",
        type: "post",
        data: values ,
        success: function (response) {

           // You will get response from your PHP page (what you echo or print)
        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }
    });

Method 2

/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
    var ajaxRequest;

    /* Stop form from submitting normally */
    event.preventDefault();

    /* Clear result div*/
    $("#result").html('');

    /* Get from elements values */
    var values = $(this).serialize();

    /* Send the data using post and put the results in a div. */
    /* I am not aborting the previous request, because it's an
       asynchronous request, meaning once it's sent it's out
       there. But in case you want to abort it you can do it
       by abort(). jQuery Ajax methods return an XMLHttpRequest
       object, so you can just use abort(). */
       ajaxRequest= $.ajax({
            url: "test.php",
            type: "post",
            data: values
        });

    /*  Request can be aborted by ajaxRequest.abort() */

    ajaxRequest.done(function (response, textStatus, jqXHR){

         // Show successfully for submit message
         $("#result").html('Submitted successfully');
    });

    /* On failure of request this function will be called  */
    ajaxRequest.fail(function (){

        // Show error
        $("#result").html('There is error while submit');
    });

The .success(), .error(), and .complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use .done(), .fail(), and .always() instead.

MDN: abort() . If the request has been sent already, this method will abort the request.

So we have successfully send an Ajax request, and now it's time to grab data to server.

PHP

As we make a POST request in an Ajax call (type: "post"), we can now grab data using either $_REQUEST or $_POST:

  $bar = $_POST['bar']

You can also see what you get in the POST request by simply either. BTW, make sure that $_POST is set. Otherwise you will get an error.

var_dump($_POST);
// Or
print_r($_POST);

And you are inserting a value into the database. Make sure you are sensitizing or escaping All requests (whether you made a GET or POST) properly before making the query. The best would be using prepared statements.

And if you want to return any data back to the page, you can do it by just echoing that data like below.

// 1. Without JSON
   echo "Hello, this is one"

// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));

And then you can get it like:

 ajaxRequest.done(function (response){
    alert(response);
 });

There are a couple of shorthand methods. You can use the below code. It does the same work.

var ajaxRequest= $.post("test.php", values, function(data) {
  alert(data);
})
  .fail(function() {
    alert("error");
  })
  .always(function() {
    alert("finished");
});

Parse JSON with R

Here is the missing example

library(rjson)
url <- 'http://someurl/data.json'
document <- fromJSON(file=url, method='C')

HTTPS using Jersey Client

For Jersey 2 you'd need to modify the code:

        return ClientBuilder.newBuilder()
            .withConfig(config)
            .hostnameVerifier(new TrustAllHostNameVerifier())
            .sslContext(ctx)
            .build();

https://gist.github.com/JAlexoid/b15dba31e5919586ae51 http://www.panz.in/2015/06/jersey2https.html

JavaScript chop/slice/trim off last character in string

Use substring to get everything to the left of _bar. But first you have to get the instr of _bar in the string:

str.substring(3, 7);

3 is that start and 7 is the length.

Submitting a form by pressing enter without a submit button

The most elegant way of doing this is to keep the submit-button, but set it's border, padding and font-size to 0.

This will make the button dimensions 0x0.

<input type="submit" style="border:0; padding:0; font-size:0">

You can try this yourself, and by setting an outline to the element you will see a dot, which is the outside border "surrounding" the 0x0 px element.

No need for visibility:hidden, but if it makes you sleep at night, you can throw that in the mix as well.

JS Fiddle

jQuery: print_r() display equivalent?

I've made a jQuery plugin for the equivalent of

<pre>
<?php echo print_r($data) ?>
</pre>

You can download it at https://github.com/tomasvanrijsse/jQuery.dump

String comparison in Python: is vs. ==

For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.

Not always. NaN is a counterexample. But usually, identity (is) implies equality (==). The converse is not true: Two distinct objects can have the same value.

Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values?

You use == when comparing values and is when comparing identities.

When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is, but don't rely on it.

For boolean values, you shouldn't be doing comparisons at all. Instead of:

if x == True:
    # do something

write:

if x:
    # do something

For comparing against None, is None is preferred over == None.

I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.

Yes, that's exactly what it's for.

Error: Unexpected value 'undefined' imported by the module

I had the same error, none of above tips didn't help.

In my case, it was caused by WebStorm, combined two imports into one.

import { ComponentOne, ComponentTwo } from '../component-dir';

I extracted this into two separate imports

import { ComponentOne } from '../component-dir/component-one.service';
import { ComponentTwo } from '../component-dir/component-two.model';

After this it works without error.

PostgreSQL database default location on Linux

Below query will help to find postgres configuration file.

postgres=# SHOW config_file;
             config_file
-------------------------------------
 /var/lib/pgsql/data/postgresql.conf
(1 row)

[root@node1 usr]# cd /var/lib/pgsql/data/
[root@node1 data]# ls -lrth
total 48K
-rw------- 1 postgres postgres    4 Nov 25 13:58 PG_VERSION
drwx------ 2 postgres postgres    6 Nov 25 13:58 pg_twophase
drwx------ 2 postgres postgres    6 Nov 25 13:58 pg_tblspc
drwx------ 2 postgres postgres    6 Nov 25 13:58 pg_snapshots
drwx------ 2 postgres postgres    6 Nov 25 13:58 pg_serial
drwx------ 4 postgres postgres   36 Nov 25 13:58 pg_multixact
-rw------- 1 postgres postgres  20K Nov 25 13:58 postgresql.conf
-rw------- 1 postgres postgres 1.6K Nov 25 13:58 pg_ident.conf
-rw------- 1 postgres postgres 4.2K Nov 25 13:58 pg_hba.conf
drwx------ 3 postgres postgres   60 Nov 25 13:58 pg_xlog
drwx------ 2 postgres postgres   18 Nov 25 13:58 pg_subtrans
drwx------ 2 postgres postgres   18 Nov 25 13:58 pg_clog
drwx------ 5 postgres postgres   41 Nov 25 13:58 base
-rw------- 1 postgres postgres   92 Nov 25 14:00 postmaster.pid
drwx------ 2 postgres postgres   18 Nov 25 14:00 pg_notify
-rw------- 1 postgres postgres   57 Nov 25 14:00 postmaster.opts
drwx------ 2 postgres postgres   32 Nov 25 14:00 pg_log
drwx------ 2 postgres postgres 4.0K Nov 25 14:00 global
drwx------ 2 postgres postgres   25 Nov 25 14:20 pg_stat_tmp

Pretty-print a Map in Java

Using Java 8 Streams:

Map<Object, Object> map = new HashMap<>();

String content = map.entrySet()
                    .stream()
                    .map(e -> e.getKey() + "=\"" + e.getValue() + "\"")
                    .collect(Collectors.joining(", "));

System.out.println(content);

How to retrieve the first word of the output of a command in bash?

You could try awk

echo "word1 word2" | awk '{ print $1 }'

With awk it is really easy to pick any word you like ($1, $2, ...)

How would you do a "not in" query with LINQ?

You can use a combination of Where and Any for finding not in:

var NotInRecord =list1.Where(p => !list2.Any(p2 => p2.Email  == p.Email));

How to import a bak file into SQL Server Express

There is a step by step explanation (with pictures) available @ Restore DataBase

  1. Click Start, select All Programs, click Microsoft SQL Server 2008 and select SQL Server Management Studio.
    This will bring up the Connect to Server dialog box.
    Ensure that the Server name YourServerName and that Authentication is set to Windows Authentication.
    Click Connect.

  2. On the right, right-click Databases and select Restore Database.
    This will bring up the Restore Database window.

  3. On the Restore Database screen, select the From Device radio button and click the "..." box.
    This will bring up the Specify Backup screen.

  4. On the Specify Backup screen, click Add.
    This will bring up the Locate Backup File.

  5. Select the DBBackup folder and chose your BackUp File(s).

  6. On the Restore Database screen, under Select the backup sets to restore: place a check in the Restore box, next to your data and in the drop-down next to To database: select DbName.

  7. You're done.

Remove all constraints affecting a UIView

I use the following method to remove all constraints from a view:

.h file:

+ (void)RemoveContraintsFromView:(UIView*)view 
    removeParentConstraints:(bool)parent 
    removeChildConstraints:(bool)child;

.m file:

+ (void)RemoveContraintsFromView:(UIView *)view 
    removeParentConstraints:(bool)parent 
    removeChildConstraints:(bool)child
{
    if (parent) {
        // Remove constraints between view and its parent.
        UIView *superview = view.superview;
        [view removeFromSuperview];
        [superview addSubview:view];
    }

    if (child) {
        // Remove constraints between view and its children.
        [view removeConstraints:[view constraints]];
    }
}

You can also read this post on my blog to better understand how it works behind the hood.

If you need more granular control, I'd strongly advise switching to Masonry, a powerful framework class you could use whenever you need to properly handle constraints programmatically.