Programs & Examples On #Addition

Addition is a mathematical operation that represents combining collections of objects together into a larger collection. It is signified by the plus sign (+).

How to force addition instead of concatenation in javascript

The following statement appends the value to the element with the id of response

$('#response').append(total);

This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element

change that to

$('#response').text(total);

You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following

$(function() {
    var data = [];
    var total = 0;

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

    $("#droppable_box").droppable({
        drop: function(event, ui) {
        var currentId = $(ui.draggable).attr('id');
        data.push($(ui.draggable).attr('id'));

        if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
        }
        if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
        }
        if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
        }
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
            myInt1 = parseInt(0);
        }
        if ( typeof myInt2 === 'undefined' || !myInt2){
            myInt2 = parseInt(0);
        }
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        }
        total += parseFloat(myInt1 + myInt2 + myInt3);
        $('#response').text(total);
        }
    });

    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {
            alert(data);
            //alert(total);
        });
    });
});

I moved the var total = 0; statement out of the drop event and changed the assignment statment from this

total = parseFloat(myInt1 + myInt2 + myInt3);

to this

total += parseFloat(myInt1 + myInt2 + myInt3);

Here is a working example http://jsfiddle.net/axrwkr/RCzGn/

How to find difference between two columns data?

select previous, Present, previous-Present as Difference from tablename

or

select previous, Present, previous-Present as Difference from #TEMP1

How to force JS to do math instead of putting two strings together

Number()

dots = document.getElementById("txt").value;
dots = Number(dots) + 5;

// from MDN
Number('123')     // 123
Number('123') === 123 /// true
Number('12.3')    // 12.3
Number('12.00')   // 12
Number('123e-1')  // 12.3
Number('')        // 0
Number(null)      // 0
Number('0x11')    // 17
Number('0b11')    // 3
Number('0o11')    // 9
Number('foo')     // NaN
Number('100a')    // NaN
Number('-Infinity') //-Infinity

Time calculation in php (add 10 hours)?

$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.

see DateTime Class (PHP 5 >= 5.2.0)

Access Controller method from another controller in Laravel 5

Try creating a new PrintReportController object in SubmitPerformanceController and calling getPrintReport method directly.

For example lets say I have a function called "Test" in SubmitPerformanceController then I can do something like this:

public function test() { 
  $prc = new PrintReportController();
  $prc->getPrintReport();
 }

Changing Jenkins build number

Under the job workspace folder, like:

C:\Program Files (x86)\Jenkins\jobs\job_name

there is a file named nextBuildNumber.

Setting the build number in the file and reloading the configuration from disk (Manage Jenkins menu) will force the next build you start to have the value from the file as BUILD_NUMBER.

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

How is Pythons glob.glob ordered?

If you're wondering about what glob.glob has done on your system in the past and cannot add a sorted call, the ordering will be consistent on Mac HFS+ filesystems and will be traversal order on other Unix systems. So it will likely have been deterministic unless the underlying filesystem was reorganized which can happen if files were added, removed, renamed, deleted, moved, etc...

SQL How to replace values of select return?

I got the solution

   SELECT 
   CASE status
      WHEN 'VS' THEN 'validated by subsidiary'
      WHEN 'NA' THEN 'not acceptable'
      WHEN 'D'  THEN 'delisted'
      ELSE 'validated'
   END AS STATUS
   FROM SUPP_STATUS

This is using the CASE This is another to manipulate the selected value for more that two options.

How to do one-liner if else statement?

You can use a closure for this:

func doif(b bool, f1, f2 func()) {
    switch{
    case b:
        f1()
    case !b:   
        f2()
    }
}

func dothis() { fmt.Println("Condition is true") }

func dothat() { fmt.Println("Condition is false") }

func main () {
    condition := true
    doif(condition, func() { dothis() }, func() { dothat() })
}

The only gripe I have with the closure syntax in Go is there is no alias for the default zero parameter zero return function, then it would be much nicer (think like how you declare map, array and slice literals with just a type name).

Or even the shorter version, as a commenter just suggested:

func doif(b bool, f1, f2 func()) {
    switch{
    case b:
        f1()
    case !b:   
        f2()
    }
}

func dothis() { fmt.Println("Condition is true") }

func dothat() { fmt.Println("Condition is false") }

func main () {
    condition := true
    doif(condition, dothis, dothat)
}

You would still need to use a closure if you needed to give parameters to the functions. This could be obviated in the case of passing methods rather than just functions I think, where the parameters are the struct associated with the methods.

Create a custom View by inflating a layout?

A bit old, but I thought sharing how I'd do it, based on chubbsondubs' answer: I use FrameLayout (see Documentation), since it is used to contain a single view, and inflate into it the view from the xml.

Code following:

public class MyView extends FrameLayout {
    public MyView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView();
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public MyView(Context context) {
        super(context);
        initView();
    }

    private void initView() {
        inflate(getContext(), R.layout.my_view_layout, this);
    }
}

How to validate phone number using PHP?

I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....

Take a look at this similar question to get some ideas.

Then there is E.164 which is a numbering standard recommendation from ITU-T

How do you open a file in C++?

You need to use an ifstream if you just want to read (use an ofstream to write, or an fstream for both).

To open a file in text mode, do the following:

ifstream in("filename.ext", ios_base::in); // the in flag is optional

To open a file in binary mode, you just need to add the "binary" flag.

ifstream in2("filename2.ext", ios_base::in | ios_base::binary ); 

Use the ifstream.read() function to read a block of characters (in binary or text mode). Use the getline() function (it's global) to read an entire line.

Difference between if () { } and if () : endif;

I think that it's particularly clearer when you're using a mix of ifs, fors and foreaches in view scripts:

<?php if ( $this->hasIterable ): ?>
    <h2>Iterable</h2>
    <ul>
    <?php foreach ( $this->iterable as $key => $val ):?>
        <?php for ( $i = 0; $i <= $val; $i++ ): ?>
        <li><?php echo $key ?></li>
        <?php endfor; ?>
    <?php endforeach; ?>
    </ul>
<?php elseif ( $this->hasScalar ): ?>
    <h2>Scalar</h2>
    <?php for ( $i = 0; $i <= $this->scalar; $i++ ): ?>
    <p>Foo = Bar</p>
    <?php endfor; ?>
<?php else: ?>
    <h2>Other</h2>
    <?php if ( $this->otherVal === true ): ?>
    <p>Spam</p>
    <?php else: ?>  
    <p>Eggs</p>  
    <?php endif; ?>
<?php endif; ?>

as opposed to:

<?php if ( $this->hasIterable ){ ?>
    <h2>Iterable</h2>
    <ul>
    <?php foreach ( $this->iterable as $key => $val ){?>
        <?php for ( $i = 0; $i <= $val; $i++ ){ ?>
        <li><?php echo $key ?></li>
        <?php } ?>
    <?php } ?>
    </ul>
<?php } elseif ( $this->hasScalar ){ ?>
    <h2>Scalar</h2>
    <?php for ( $i = 0; $i <= $this->scalar; $i++ ){ ?>
    <p>Foo = Bar</p>
    <?php } ?>
<?php } else { ?>
    <h2>Other</h2>
    <?php if ( $this->otherVal === true ){ ?>
    <p>Spam</p>
    <?php } else { ?>  
    <p>Eggs</p>  
    <?php } ?>
<?php } ?>

This is especially useful for long control statements where you might not be able to see the top declaration from the bottom brace.

How can I check that two objects have the same set of property names?

If you want to check if both objects have the same properties name, you can do this:

function hasSameProps( obj1, obj2 ) {
  return Object.keys( obj1 ).every( function( prop ) {
    return obj2.hasOwnProperty( prop );
  });
}

var obj1 = { prop1: 'hello', prop2: 'world', prop3: [1,2,3,4,5] },
    obj2 = { prop1: 'hello', prop2: 'world', prop3: [1,2,3,4,5] };

console.log(hasSameProps(obj1, obj2));

In this way you are sure to check only iterable and accessible properties of both the objects.

EDIT - 2013.04.26:

The previous function can be rewritten in the following way:

function hasSameProps( obj1, obj2 ) {
    var obj1Props = Object.keys( obj1 ),
        obj2Props = Object.keys( obj2 );

    if ( obj1Props.length == obj2Props.length ) {
        return obj1Props.every( function( prop ) {
          return obj2Props.indexOf( prop ) >= 0;
        });
    }

    return false;
}

In this way we check that both the objects have the same number of properties (otherwise the objects haven't the same properties, and we must return a logical false) then, if the number matches, we go to check if they have the same properties.

Bonus

A possible enhancement could be to introduce also a type checking to enforce the match on every property.

Trigger change() event when setting <select>'s value with val() function

The straight answer is already in a duplicate question: Why does the jquery change event not trigger when I set the value of a select using val()?

As you probably know setting the value of the select doesn't trigger the change() event, if you're looking for an event that is fired when an element's value has been changed through JS there isn't one.

If you really want to do this I guess the only way is to write a function that checks the DOM on an interval and tracks changed values, but definitely don't do this unless you must (not sure why you ever would need to)

Added this solution:
Another possible solution would be to create your own .val() wrapper function and have it trigger a custom event after setting the value through .val(), then when you use your .val() wrapper to set the value of a <select> it will trigger your custom event which you can trap and handle.

Be sure to return this, so it is chainable in jQuery fashion

What is the use of "object sender" and "EventArgs e" parameters?

Those two parameters (or variants of) are sent, by convention, with all events.

  • sender: The object which has raised the event
  • e an instance of EventArgs including, in many cases, an object which inherits from EventArgs. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.

In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs are Empty as there is no further information about the event.

Looking at the 2 parameters separately, here are some examples where they are useful.

sender

Say you have multiple buttons on a form. These buttons could contain a Tag describing what clicking them should do. You could handle all the Click events with the same handler, and depending on the sender do something different

private void HandleButtonClick(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    if(btn.Tag == "Hello")
      MessageBox.Show("Hello")
    else if(btn.Tag == "Goodbye")
       Application.Exit();
    // etc.
}

Disclaimer : That's a contrived example; don't do that!

e

Some events are cancelable. They send CancelEventArgs instead of EventArgs. This object adds a simple boolean property Cancel on the event args. Code handling this event can cancel the event:

private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
    if(/* some condition*/)
    {
       // Cancel this event
       e.Cancel = true;
    }
}

How can I make a DateTimePicker display an empty string?

The basic concept is the same told by others. But its easier to implement this way when you have multiple dateTimePicker.

dateTimePicker1.Value = DateTime.Now;
dateTimePicker1.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker1.ShowCheckBox=true;
dateTimePicker1.Checked=false;


dateTimePicker2.Value = DateTime.Now;
dateTimePicker2.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker2.ShowCheckBox=true;
dateTimePicker2.Checked=false;

the value changed event function

        void Dtp_ValueChanged(object sender, EventArgs e)
        {
            if(((DateTimePicker)sender).ShowCheckBox==true)
            {
                if(((DateTimePicker)sender).Checked==false)
                {
                    ((DateTimePicker)sender).CustomFormat = " ";
                    ((DateTimePicker)sender).Format = DateTimePickerFormat.Custom;
                }
                else
                {
                    ((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
                }
            }
            else
            {
                ((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
            }
        }

When unchecked enter image description here

When checked enter image description here

use Lodash to sort array of object by value

You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).

Your code could be like:

const myArray = [  
   {  
      "id":25,
      "name":"Anakin Skywalker",
      "createdAt":"2017-04-12T12:48:55.000Z",
      "updatedAt":"2017-04-12T12:48:55.000Z"
   },
   {  
      "id":1,
      "name":"Luke Skywalker",
      "createdAt":"2017-04-12T11:25:03.000Z",
      "updatedAt":"2017-04-12T11:25:03.000Z"
   }
]

const myOrderedArray = _.sortBy(myArray, o => o.name)

Cast Int to enum in Java

MyEnum.values()[x] is an expensive operation. If the performance is a concern, you may want to do something like this:

public enum MyEnum {
    EnumValue1,
    EnumValue2;

    public static MyEnum fromInteger(int x) {
        switch(x) {
        case 0:
            return EnumValue1;
        case 1:
            return EnumValue2;
        }
        return null;
    }
}

Run AVD Emulator without Android Studio

Open your terminal and

cd path_to/Android/Sdk/emulator

And run the following to get the emulator name that you created before using android studio

./emulator -list-avds

Replace $emulator_name with the one you want to launch and run

./emulator -avd $emulator_name

How to compare two Carbon Timestamps?

This is how I am comparing 2 dates, now() and a date from the table

@if (\Carbon\Carbon::now()->lte($item->client->event_date_from))
    .....
    .....
@endif

Should work just right. I have used the comparison functions provided by Carbon.

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

An expansion for those who did a bit of fiddling around like I did.

The following work (from W3):

<input type="text" autofocus />
<input type="text" autofocus="" />
<input type="text" autofocus="autofocus" />
<input type="text" autofocus="AuToFoCuS" />

It is important to note that this does not work in CSS though. I.e. you can't use:

.first-input {
    autofocus:"autofocus"
}

At least it didn't work for me...

How to target the href to div

Try this code in jquery

$(document).ready(function(){
  $("a").click(function(){
  var id=$(this).attr('href');
  var value=$(id).text();
  $(".target").text(value);
  });
});

How do I pass named parameters with Invoke-Command?

I suspect its a new feature since this post was created - pass parameters to the script block using $Using:var. Then its a simple mater to pass parameters provided the script is already on the machine or in a known network location relative to the machine

Taking the main example it would be:

icm -cn $Env:ComputerName { 
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -one "uno" -two "dos" -Debug -Clear $Using:Clear
}

How to Rotate a UIImage 90 degrees?

Check out the simple and awesome code of Hardy Macia at: cutting-scaling-and-rotating-uiimages

Just call

UIImage *rotatedImage = [originalImage imageRotatedByDegrees:90.0];

Thanks Hardy Macia!

Header:

  • (UIImage *)imageAtRect:(CGRect)rect;
  • (UIImage *)imageByScalingProportionallyToMinimumSize:(CGSize)targetSize;
  • (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
  • (UIImage *)imageByScalingToSize:(CGSize)targetSize;
  • (UIImage *)imageRotatedByRadians:(CGFloat)radians;
  • (UIImage *)imageRotatedByDegrees:(CGFloat)degrees;

Since the link may die, here's the complete code

//
//  UIImage-Extensions.h
//
//  Created by Hardy Macia on 7/1/09.
//  Copyright 2009 Catamount Software. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface UIImage (CS_Extensions)
- (UIImage *)imageAtRect:(CGRect)rect;
- (UIImage *)imageByScalingProportionallyToMinimumSize:(CGSize)targetSize;
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
- (UIImage *)imageByScalingToSize:(CGSize)targetSize;
- (UIImage *)imageRotatedByRadians:(CGFloat)radians;
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees;

@end;

//
//  UIImage-Extensions.m
//
//  Created by Hardy Macia on 7/1/09.
//  Copyright 2009 Catamount Software. All rights reserved.
//

#import "UIImage-Extensions.h"

CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
CGFloat RadiansToDegrees(CGFloat radians) {return radians * 180/M_PI;};

@implementation UIImage (CS_Extensions)

-(UIImage *)imageAtRect:(CGRect)rect
{

   CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
   UIImage* subImage = [UIImage imageWithCGImage: imageRef];
   CGImageRelease(imageRef);

   return subImage;

}

- (UIImage *)imageByScalingProportionallyToMinimumSize:(CGSize)targetSize {

   UIImage *sourceImage = self;
   UIImage *newImage = nil;

   CGSize imageSize = sourceImage.size;
   CGFloat width = imageSize.width;
   CGFloat height = imageSize.height;

   CGFloat targetWidth = targetSize.width;
   CGFloat targetHeight = targetSize.height;

   CGFloat scaleFactor = 0.0;
   CGFloat scaledWidth = targetWidth;
   CGFloat scaledHeight = targetHeight;

   CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

   if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

      CGFloat widthFactor = targetWidth / width;
      CGFloat heightFactor = targetHeight / height;

      if (widthFactor > heightFactor) 
         scaleFactor = widthFactor;
      else
         scaleFactor = heightFactor;

      scaledWidth  = width * scaleFactor;
      scaledHeight = height * scaleFactor;

      // center the image

      if (widthFactor > heightFactor) {
         thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
      } else if (widthFactor < heightFactor) {
         thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
      }
   }


   // this is actually the interesting part:

   UIGraphicsBeginImageContext(targetSize);

   CGRect thumbnailRect = CGRectZero;
   thumbnailRect.origin = thumbnailPoint;
   thumbnailRect.size.width  = scaledWidth;
   thumbnailRect.size.height = scaledHeight;

   [sourceImage drawInRect:thumbnailRect];

   newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if(newImage == nil) NSLog(@"could not scale image");


   return newImage ;
}


- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {

   UIImage *sourceImage = self;
   UIImage *newImage = nil;

   CGSize imageSize = sourceImage.size;
   CGFloat width = imageSize.width;
   CGFloat height = imageSize.height;

   CGFloat targetWidth = targetSize.width;
   CGFloat targetHeight = targetSize.height;

   CGFloat scaleFactor = 0.0;
   CGFloat scaledWidth = targetWidth;
   CGFloat scaledHeight = targetHeight;

   CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

   if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

      CGFloat widthFactor = targetWidth / width;
      CGFloat heightFactor = targetHeight / height;

      if (widthFactor < heightFactor) 
         scaleFactor = widthFactor;
      else
         scaleFactor = heightFactor;

      scaledWidth  = width * scaleFactor;
      scaledHeight = height * scaleFactor;

      // center the image

      if (widthFactor < heightFactor) {
         thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
      } else if (widthFactor > heightFactor) {
         thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
      }
   }


   // this is actually the interesting part:

   UIGraphicsBeginImageContext(targetSize);

   CGRect thumbnailRect = CGRectZero;
   thumbnailRect.origin = thumbnailPoint;
   thumbnailRect.size.width  = scaledWidth;
   thumbnailRect.size.height = scaledHeight;

   [sourceImage drawInRect:thumbnailRect];

   newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if(newImage == nil) NSLog(@"could not scale image");


   return newImage ;
}


- (UIImage *)imageByScalingToSize:(CGSize)targetSize {

   UIImage *sourceImage = self;
   UIImage *newImage = nil;

   //   CGSize imageSize = sourceImage.size;
   //   CGFloat width = imageSize.width;
   //   CGFloat height = imageSize.height;

   CGFloat targetWidth = targetSize.width;
   CGFloat targetHeight = targetSize.height;

   //   CGFloat scaleFactor = 0.0;
   CGFloat scaledWidth = targetWidth;
   CGFloat scaledHeight = targetHeight;

   CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

   // this is actually the interesting part:

   UIGraphicsBeginImageContext(targetSize);

   CGRect thumbnailRect = CGRectZero;
   thumbnailRect.origin = thumbnailPoint;
   thumbnailRect.size.width  = scaledWidth;
   thumbnailRect.size.height = scaledHeight;

   [sourceImage drawInRect:thumbnailRect];

   newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if(newImage == nil) NSLog(@"could not scale image");


   return newImage ;
}


- (UIImage *)imageRotatedByRadians:(CGFloat)radians
{
   return [self imageRotatedByDegrees:RadiansToDegrees(radians)];
}

- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees 
{   
   // calculate the size of the rotated view's containing box for our drawing space
   UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)];
   CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
   rotatedViewBox.transform = t;
   CGSize rotatedSize = rotatedViewBox.frame.size;
   [rotatedViewBox release];

   // Create the bitmap context
   UIGraphicsBeginImageContext(rotatedSize);
   CGContextRef bitmap = UIGraphicsGetCurrentContext();

   // Move the origin to the middle of the image so we will rotate and scale around the center.
   CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

   //   // Rotate the image context
   CGContextRotateCTM(bitmap, DegreesToRadians(degrees));

   // Now, draw the rotated/scaled image into the context
   CGContextScaleCTM(bitmap, 1.0, -1.0);
   CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]);

   UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   return newImage;

}

@end;

No such keg: /usr/local/Cellar/git

Give another go at force removing the brewed version of git

brew uninstall --force git

Then cleanup any older versions and clear the brew cache

brew cleanup -s git

Remove any dead symlinks

brew cleanup --prune-prefix

Then try reinstalling git

brew install git

If that doesn't work, I'd remove that installation of Homebrew altogether and reinstall it. If you haven't placed anything else in your brew --prefix directory (/usr/local by default), you can simply rm -rf $(brew --prefix). Otherwise the Homebrew wiki recommends using a script at https://gist.github.com/mxcl/1173223#file-uninstall_homebrew-sh

android get all contacts

Try this too,

private void getContactList() {
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);

    if ((cur != null ? cur.getCount() : 0) > 0) {
        while (cur != null && cur.moveToNext()) {
            String id = cur.getString(
                    cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(
                    ContactsContract.Contacts.DISPLAY_NAME));

            if (cur.getInt(cur.getColumnIndex(
                    ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                Cursor pCur = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                        new String[]{id}, null);
                while (pCur.moveToNext()) {
                    String phoneNo = pCur.getString(pCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER));
                    Log.i(TAG, "Name: " + name);
                    Log.i(TAG, "Phone Number: " + phoneNo);
                }
                pCur.close();
            }
        }
    }
    if(cur!=null){
        cur.close();
    }
}

If you need more reference means refer this link Read ContactList

matching query does not exist Error in Django

You can use this in your case, it will work fine.

user = UniversityDetails.objects.filter(email=email).first()

Parsing JSON from XmlHttpRequest.responseJSON

I think you have to include jQuery to use responseJSON.

Without jQuery, you could try with responseText and try like eval("("+req.responseText+")");

UPDATE:Please read the comment regarding eval, you can test with eval, but don't use it in working extension.

OR

use json_parse : it does not use eval

TypeScript Objects as Dictionary types as in C#

In newer versions of typescript you can use:

type Customers = Record<string, Customer>

In older versions you can use:

var map: { [email: string]: Customer; } = { };
map['[email protected]'] = new Customer(); // OK
map[14] = new Customer(); // Not OK, 14 is not a string
map['[email protected]'] = 'x'; // Not OK, 'x' is not a customer

You can also make an interface if you don't want to type that whole type annotation out every time:

interface StringToCustomerMap {
    [email: string]: Customer;
}

var map: StringToCustomerMap = { };
// Equivalent to first line of above

How can I show dots ("...") in a span with hidden overflow?

Thanks a lot @sandeep for his answer.

My problem was that I want to show / hide text on span with mouse click. So by default short text with dots is shown and by clicking long text appears. Clicking again hides that long text and shows short one again.

Quite easy thing to do: just add / remove class with text-overflow:ellipsis.

HTML:

<span class="spanShortText cursorPointer"  onclick="fInventoryShippingReceiving.ShowHideTextOnSpan(this);">Some really long description here</span>

CSS (same as @sandeep with .cursorPointer added)

.spanShortText {
  display: inline-block;
  width: 100px;
  white-space: nowrap;
  overflow: hidden !important;
  text-overflow: ellipsis;
}

.cursorPointer {
  cursor: pointer;
}

JQuery part - basically just removes / adds class cSpanShortText.

  function ShowHideTextOnSpan(element) {
    var cSpanShortText = 'spanShortText';
    var $el = $(element);
    if ($el.hasClass(cSpanShortText)) {
      $el.removeClass(cSpanShortText)
    } else {
      $el.addClass(cSpanShortText);
    }
  }

isolating a sub-string in a string before a symbol in SQL Server 2008

This can achieve using two SQL functions- SUBSTRING and CHARINDEX

You can read strings to a variable as shown in the above answers, or can add it to a SELECT statement as below:

SELECT SUBSTRING('Net Operating Loss - 2007' ,0, CHARINDEX('-','Net Operating Loss - 2007'))

Linux: where are environment variables stored?

Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)

Is it possible to preview stash contents in git?

When this question was first asked, this may not have been an option, but, if you use PyCharm, you can use the UnStash Changes tool (VCS->Git->UnStash Changes...). This allows you to view the list of stashed changes, as well as pop, drop, clear, or apply (into a new branch if desired):

Unstash Changes Window

and view the changed files per stash:

Paths Affected Window

as well as diffs per file. In the diffs you can cherry-pick individual changes to apply from the stashed changes to the working branch (using the left-pointing chevron):

enter image description here

Xcode 8 shows error that provisioning profile doesn't include signing certificate

For those who should keep using not auotamatic for some reason

Open keyChain Access to see whether there are two same Certifications ,If there's two or more,Just Delete to one and it will work :)

What is memoization and how can I use it in Python?

Memoization is the conversion of functions into data structures. Usually one wants the conversion to occur incrementally and lazily (on demand of a given domain element--or "key"). In lazy functional languages, this lazy conversion can happen automatically, and thus memoization can be implemented without (explicit) side-effects.

Change connection string & reload app.config at run time

IIRC, the ConfigurationManager.RefreshSection requires a string parameter specifying the name of the Section to refresh :

ConfigurationManager.RefreshSection("connectionStrings");

I think that the ASP.NET application should automatically reload when the ConnectionStrings element is modified and the configuration does not need to be manually reloaded.

removing html element styles via javascript

In jQuery, you can use

$(".className").attr("style","");

Explode string by one or more spaces or tabs

This works:

$string = 'A   B C          D';
$arr = preg_split('/[\s]+/', $string);

npm throws error without sudo

Actually, I was also having the same problem. I was running Ubuntu. Mine problem arises because I'd lost my public key of the Ubuntu. Even updating my system was not happening. It was giving GPG error. In that case, you can regain your key by using this command:

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys <key in GPG error>

After that npm works fine!

Get drop down value

If your dropdown is something like this:

<select id="thedropdown">
  <option value="1">one</option>
  <option value="2">two</option>
</select>

Then you would use something like:

var a = document.getElementById("thedropdown");
alert(a.options[a.selectedIndex].value);

But a library like jQuery simplifies things:

alert($('#thedropdown').val());

Egit rejected non-fast-forward

  1. Go in Github an create a repo for your new code.
  2. Use the new https or ssh url in Eclise when you are doing the push to upstream;

AngularJS- Login and Authentication in each route and controller

app.js

'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute','angularUtils.directives.dirPagination','ngLoadingSpinner']);
app.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
  $routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
  $routeProvider.when('/salesnew', {templateUrl: 'partials/salesnew.html', controller: 'salesnewCtrl'});
  $routeProvider.when('/salesview', {templateUrl: 'partials/salesview.html', controller: 'salesviewCtrl'});
  $routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'usersCtrl'});
    $routeProvider.when('/forgot', {templateUrl: 'partials/forgot.html', controller: 'forgotCtrl'});


  $routeProvider.otherwise({redirectTo: '/login'});


}]);


app.run(function($rootScope, $location, loginService){
    var routespermission=['/home'];  //route that require login
    var salesnew=['/salesnew'];
    var salesview=['/salesview'];
    var users=['/users'];
    $rootScope.$on('$routeChangeStart', function(){
        if( routespermission.indexOf($location.path()) !=-1
        || salesview.indexOf($location.path()) !=-1
        || salesnew.indexOf($location.path()) !=-1
        || users.indexOf($location.path()) !=-1)
        {
            var connected=loginService.islogged();
            connected.then(function(msg){
                if(!msg.data)
                {
                    $location.path('/login');
                }

            });
        }
    });
});

loginServices.js

'use strict';
app.factory('loginService',function($http, $location, sessionService){
    return{
        login:function(data,scope){
            var $promise=$http.post('data/user.php',data); //send data to user.php
            $promise.then(function(msg){
                var uid=msg.data;
                if(uid){
                    scope.msgtxt='Correct information';
                    sessionService.set('uid',uid);
                    $location.path('/home');
                }          
                else  {
                    scope.msgtxt='incorrect information';
                    $location.path('/login');
                }                  
            });
        },
        logout:function(){
            sessionService.destroy('uid');
            $location.path('/login');
        },
        islogged:function(){
            var $checkSessionServer=$http.post('data/check_session.php');
            return $checkSessionServer;
            /*
            if(sessionService.get('user')) return true;
            else return false;
            */
        }
    }

});

sessionServices.js

'use strict';

app.factory('sessionService', ['$http', function($http){
    return{
        set:function(key,value){
            return sessionStorage.setItem(key,value);
        },
        get:function(key){
            return sessionStorage.getItem(key);
        },
        destroy:function(key){
            $http.post('data/destroy_session.php');
            return sessionStorage.removeItem(key);
        }
    };
}])

loginCtrl.js

'use strict';

app.controller('loginCtrl', ['$scope','loginService', function ($scope,loginService) {
    $scope.msgtxt='';
    $scope.login=function(data){
        loginService.login(data,$scope); //call login service
    };

}]);

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

Given the Class loader sussystem actions:

http://www.artima.com/insidejvm/ed2/images/fig7-1.gif

This is an article that helped me a lot to understand the difference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html

If an error occurs during class loading, then an instance of a subclass of LinkageError must be thrown at a point in the program that (directly or indirectly) uses the class or interface being loaded.

If the Java Virtual Machine ever attempts to load a class C during verification (§5.4.1) or resolution (§5.4.3) (but not initialization (§5.5)), and the class loader that is used to initiate loading of C throws an instance of ClassNotFoundException, then the Java Virtual Machine must throw an instance of NoClassDefFoundError whose cause is the instance of ClassNotFoundException.

So a ClassNotFoundException is a root cause of NoClassDefFoundError.
And a NoClassDefFoundError is a special case of type loading error, that occurs at Linking step.

How can a divider line be added in an Android RecyclerView?

Just add a View by the end of you item adapter:

<View
 android:layout_width="match_parent"
 android:layout_height="1dp"
 android:background="#FFFFFF"/>

How to POST a JSON object to a JAX-RS service

The answer was surprisingly simple. I had to add a Content-Type header in the POST request with a value of application/json. Without this header Jersey did not know what to do with the request body (in spite of the @Consumes(MediaType.APPLICATION_JSON) annotation)!

How to run a stored procedure in oracle sql developer?

Consider you've created a procedure like below.

CREATE OR REPLACE PROCEDURE GET_FULL_NAME like
(
  FIRST_NAME IN VARCHAR2, 
  LAST_NAME IN VARCHAR2,
  FULL_NAME OUT VARCHAR2 
) IS 
BEGIN
  FULL_NAME:= FIRST_NAME || ' ' || LAST_NAME;
END GET_FULL_NAME;

In Oracle SQL Developer, you can run this procedure in two ways.

1. Using SQL Worksheet

Create a SQL Worksheet and write PL/SQL anonymous block like this and hit f5

DECLARE
  FULL_NAME Varchar2(50);
BEGIN
  GET_FULL_NAME('Foo', 'Bar', FULL_NAME);
  Dbms_Output.Put_Line('Full name is: ' || FULL_NAME);
END;

2. Using GUI Controls

  • Expand Procedures

  • Right click on the procudure you've created and Click Run

  • In the pop-up window, Fill the parameters and Click OK.

Cheers!

Using SSH keys inside docker container

One cross-platform solution is to use a bind mount to share the host's .ssh folder to the container:

docker run -v /home/<host user>/.ssh:/home/<docker user>/.ssh <image>

Similar to agent forwarding this approach will make the public keys accessible to the container. An additional upside is that it works with a non-root user too and will get you connected to GitHub. One caveat to consider, however, is that all contents (including private keys) from the .ssh folder will be shared so this approach is only desirable for development and only for trusted container images.

Normalizing images in OpenCV

If you want to change the range to [0, 1], make sure the output data type is float.

image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR)  # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

Hide the browse button on a input type=file

You may just without making the element hidden, simply make it transparent by making its opacity to 0.

Making the input file hidden will make it STOP working. So DON'T DO THAT..

Here you can find an example for a transparent Browse operation;

How to stop process from .BAT file?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess.exe'" Call Terminate

wmic offer even more flexibility than taskkill .With wmic Path win32_process get you can see the available fileds you can filter.

Sending simple message body + file attachment using Linux Mailx

Try this it works for me:

(echo "Hello XYX" ; uuencode /export/home/TOTAL_SI_COUNT_10042016.csv TOTAL_SI_COUNT_10042016.csv ) | mailx -s 'Script test' [email protected]

Print array elements on separate lines in Bash?

Another useful variant is pipe to tr:

echo "${my_array[@]}" | tr ' ' '\n'

This looks simple and compact

Cannot attach the file *.mdf as database

I didn't read all the responses, but if your .mdf file is NOT part of the SQL installation path, like C:\Temp, then the SQL Database Engine service account(s) will not have permission to create and write to the .ldf file or even read the .mdf file.

The solution is you have to give file system permissions to the SQL Server database engine service account that runs the SQL instance service. So for me, I gave permissions full control via Windows Explorer to my C:\Temp path that contained my .mdf file for the NT Service\MSSQL$SQLEXPRESS01 and NT Service\MSSQL$MSSQL2016 accounts.

Here is a Microsoft article that details this very issue.

Copy file from source directory to binary directory using CMake

This is what I used to copy some resource files: the copy-files is an empty target to ignore errors

 add_custom_target(copy-files ALL
    COMMAND ${CMAKE_COMMAND} -E copy_directory
    ${CMAKE_BINARY_DIR}/SOURCEDIRECTORY
    ${CMAKE_BINARY_DIR}/DESTINATIONDIRECTORY
    )

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

Just perform the following steps:

1a) Connect to mysql (via localhost)

mysql -uroot -p

1b) If the mysql server is running in Kubernetes (K8s) and being accessed via a NodePort

kubectl exec -it [pod-name] -- /bin/bash
mysql -uroot -p
  1. Create user

    CREATE USER 'user'@'%' IDENTIFIED BY 'password';

  2. Grant permissions

    GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' WITH GRANT OPTION;

  3. Flush privileges

    FLUSH PRIVILEGES;

C++ Erase vector element by value rather than by position?

How about std::remove() instead:

#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());

This combination is also known as the erase-remove idiom.

What is the correct JSON content type?

If you are using Ubuntu or Debian and you serve .json files through Apache, you might want to serve the files with the correct content type. I am doing this primarily because I want to use the Firefox extension JSONView

The Apache module mod_mime will help to do this easily. However, with Ubuntu you need to edit the file /etc/mime.types and add the line

application/json json

Then restart Apache:

sudo service apache2 restart

Accessing constructor of an anonymous class

It doesn't make any sense to have a named overloaded constructor in an anonymous class, as there would be no way to call it, anyway.

Depending on what you are actually trying to do, just accessing a final local variable declared outside the class, or using an instance initializer as shown by Arne, might be the best solution.

Android: How to turn screen on and off programmatically?

     WakeLock screenLock =    ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
    PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
    screenLock.acquire();

  //later
  screenLock.release();

//User Manifest file

Make error: missing separator

I had the missing separator file in Makefiles generated by qmake. I was porting Qt code to a different platform. I didn't have QMAKESPEC nor MAKE set. Here's the link I found the answer:

https://forum.qt.io/topic/3783/missing-separator-error-in-makefile/5

How to make the background DIV only transparent using CSS

I don't know if this has changed. But from my experience. nested elements have a maximum opacity equal to the fathers.

Which mean:

<div id="a">
<div id="b">
</div></div>

Div#a has 0.6 opacity
div#b has 1 opacity

Has #b is within #a then it's maximum opacity is always 0.6

If #b would have 0.5 opacity. In reallity it would be 0.6*0.5 == 0.3 opacity

Installing jQuery?

It tells you at the very start of the tutorial linked from the jQuery homepage.

How do I pause my shell script for a second before continuing?

read -r -p "Wait 5 seconds or press any key to continue immediately" -t 5 -n 1 -s

To continue when you press any one button

for more info check read manpage ref 1, ref 2

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.

When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.

By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:

https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790

So the solution is:

class UserVerification extends Model
{
    protected $primaryKey = 'your_key_name'; // or null

    public $incrementing = false;

    // In Laravel 6.0+ make sure to also set $keyType
    protected $keyType = 'string';
}

How can I expose more than 1 port with Docker?

Step1

In your Dockerfile, you can use the verb EXPOSE to expose multiple ports.
e.g.

EXPOSE 3000 80 443 22

Step2

You then would like to build an new image based on above Dockerfile.
e.g.

docker build -t foo:tag .

Step3

Then you can use the -p to map host port with the container port, as defined in above EXPOSE of Dockerfile.
e.g.

docker run -p 3001:3000 -p 23:22

In case you would like to expose a range of continuous ports, you can run docker like this:

docker run -it -p 7100-7120:7100-7120/tcp 

return SQL table as JSON in python

enter image description here

from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String

Base = declarative_base()
metadata = Base.metadata


class UserTable(Base):
    __tablename__ = 'UserTable'

    Id = Column("ID", Integer, primary_key=True)
    Name = Column("Name", String(100))

        
class UserTableDTO:
    def __init__(self, ob):
        self.Id = ob.Id
        self.Name = ob.Name
        
rows = dbsession.query(Table).all()

json_string = [json.loads(json.dumps(UserTableDTO(ob).__dict__, default=lambda x: str(x)))for ob in rows]
print(json_string)

Compress images on client side before uploading

I just developed a javascript library called JIC to solve that problem. It allows you to compress jpg and png on the client side 100% with javascript and no external libraries required!

You can try the demo here : http://makeitsolutions.com/labs/jic and get the sources here : https://github.com/brunobar79/J-I-C

General guidelines to avoid memory leaks in C++

Instead of managing memory manually, try to use smart pointers where applicable.
Take a look at the Boost lib, TR1, and smart pointers.
Also smart pointers are now a part of C++ standard called C++11.

Java 8 List<V> into Map<K, V>

I use this syntax

Map<Integer, List<Choice>> choiceMap = 
choices.stream().collect(Collectors.groupingBy(choice -> choice.getName()));

Conditional replacement of values in a data.frame

Since you are conditionally indexing df$est, you also need to conditionally index the replacement vector df$a:

index <- df$b == 0
df$est[index] <- (df$a[index] - 5)/2.533 

Of course, the variable index is just temporary, and I use it to make the code a bit more readible. You can write it in one step:

df$est[df$b == 0] <- (df$a[df$b == 0] - 5)/2.533 

For even better readibility, you can use within:

df <- within(df, est[b==0] <- (a[b==0]-5)/2.533)

The results, regardless of which method you choose:

df
          a b      est
1  11.77000 2 0.000000
2  10.90000 3 0.000000
3  10.32000 2 0.000000
4  10.96000 0 2.352941
5   9.90600 0 1.936834
6  10.70000 0 2.250296
7  11.43000 1 0.000000
8  11.41000 2 0.000000
9  10.48512 4 0.000000
10 11.19000 0 2.443743

As others have pointed out, an alternative solution in your example is to use ifelse.

Laravel Rule Validation for Numbers

If I correctly got what you want:

$rules = ['Fno' => 'digits_between:2,5', 'Lno' => 'numeric|min:2'];

or

$rules = ['Fno' => 'numeric|min:2|max:5', 'Lno' => 'numeric|min:2'];

For all the available rules: http://laravel.com/docs/4.2/validation#available-validation-rules

digits_between :min,max

The field under validation must have a length between the given min and max.

numeric

The field under validation must have a numeric value.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

min:value

The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

How to get bitmap from a url in android?

This should do the trick:

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
} // Author: silentnuke

Don't forget to add the internet permission in your manifest.

How do I ignore ampersands in a SQL script running from SQL Plus?

set define off <- This is the best solution I found

I also tried...

set define }

I was able to insert several records containing ampersand characters '&' but I cannot use the '}' character into the text So I decided to use "set define off" and everything works as it should.

How can I read a text file in Android?

Try this

try {
        reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
      String line="";
      String s ="";
   try 
   {
       line = reader.readLine();
   } 
   catch (IOException e) 
   {
       e.printStackTrace();
   }
      while (line != null) 
      {
       s = s + line;
       s =s+"\n";
       try 
       {
           line = reader.readLine();
       } 
       catch (IOException e) 
       {
           e.printStackTrace();
       }
    }
    tv.setText(""+s);
  }

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

I ended up writing a small script that adds the certificates to the keystores, so it is much easier to use.

You can get the latest version from https://github.com/ssbarnea/keytool-trust

#!/bin/bash
# version 1.0
# https://github.com/ssbarnea/keytool-trust
REMHOST=$1
REMPORT=${2:-443}

KEYSTORE_PASS=changeit
KEYTOOL="sudo keytool"

# /etc/java-6-sun/security/cacerts

for CACERTS in  /usr/lib/jvm/java-8-oracle/jre/lib/security/cacerts \
    /usr/lib/jvm/java-7-oracle/jre/lib/security/cacerts \
    "/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security/cacerts" \
    "/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/MacOS/itms/java/lib/security/cacerts"
do

if [ -e "$CACERTS" ]
then
    echo --- Adding certs to $CACERTS

# FYI: the default keystore is located in ~/.keystore

if [ -z "$REMHOST" ]
    then
    echo "ERROR: Please specify the server name to import the certificatin from, eventually followed by the port number, if other than 443."
    exit 1
    fi

set -e

rm -f $REMHOST:$REMPORT.pem

if openssl s_client -connect $REMHOST:$REMPORT 1>/tmp/keytool_stdout 2>/tmp/output </dev/null
        then
        :
        else
        cat /tmp/keytool_stdout
        cat /tmp/output
        exit 1
        fi

if sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' </tmp/keytool_stdout > /tmp/$REMHOST:$REMPORT.pem
        then
        :
        else
        echo "ERROR: Unable to extract the certificate from $REMHOST:$REMPORT ($?)"
        cat /tmp/output
        fi

if $KEYTOOL -list -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT >/dev/null
    then
    echo "Key of $REMHOST already found, skipping it."
    else
    $KEYTOOL -import -trustcacerts -noprompt -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -file /tmp/$REMHOST:$REMPORT.pem
    fi

if $KEYTOOL -list -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -keystore "$CACERTS" >/dev/null
    then
    echo "Key of $REMHOST already found in cacerts, skipping it."
    else
    $KEYTOOL -import -trustcacerts -noprompt -keystore "$CACERTS" -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -file /tmp/$REMHOST:$REMPORT.pem
    fi

fi

done

```

Stretch Image to Fit 100% of Div Height and Width

You're mixing notations. It should be:

<img src="folder/file.jpg" width="200" height="200">

(note, no px). Or:

<img src="folder/file.jpg" style="width: 200px; height: 200px;">

(using the style attribute) The style attribute could be replaced with the following CSS:

#mydiv img {
    width: 200px;
    height: 200px;
}

or

#mydiv img {
    width: 100%;
    height: 100%;
}

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

Grant execute permission for a user on all stored procedures in database?

USE [DATABASE]

DECLARE @USERNAME VARCHAR(500)

DECLARE @STRSQL NVARCHAR(MAX)

SET @USERNAME='[USERNAME] '
SET @STRSQL=''

select @STRSQL+=CHAR(13)+'GRANT EXECUTE ON ['+ s.name+'].['+obj.name+'] TO'+@USERNAME+';'
from
    sys.all_objects as obj
inner join
    sys.schemas s ON obj.schema_id = s.schema_id
where obj.type in ('P','V','FK')
AND s.NAME NOT IN ('SYS','INFORMATION_SCHEMA')


EXEC SP_EXECUTESQL @STRSQL

Format a message using MessageFormat.format() in Java

Using an apostrophe (Unicode: \u2019) instead of a single quote ' fixed the issue without doubling the \'.

How to convert an image to base64 encoding?

You can also do this via curl, just you need a path to an image file and pass it to the function given below..

public static function getImageDataFromUrl($url)
{
    $urlParts = pathinfo($url);
    $extension = $urlParts['extension'];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $base64 = 'data:image/' . $extension . ';base64,' . base64_encode($response);
    return $base64;

}

Storing C++ template function definitions in a .CPP file

There is nothing wrong with the example you have given. But i must say i believe it's not efficient to store function definitions in a cpp file. I only understand the need to separate the function's declaration and definition.

When used together with explicit class instantiation, the Boost Concept Check Library (BCCL) can help you generate template function code in cpp files.

MySQL Select Date Equal to Today

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
FROM users 
WHERE DATE(signup_date) = CURDATE()

Remove first 4 characters of a string with PHP

If you’re using a multi-byte character encoding and do not just want to remove the first four bytes like substr does, use the multi-byte counterpart mb_substr. This does of course will also work with single-byte strings.

How to allow users to check for the latest app version from inside the app?

Here's how to find the current and latest available versions:

       try {
            String curVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            String newVersion = curVersion;
            newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + getPackageName() + "&hl=en")
                    .timeout(30000)
                    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                    .referrer("http://www.google.com")
                    .get()
                    .select("div.hAyfc:nth-child(4) .IQ1z0d .htlgb")
                    .first()
                    .ownText();
            Log.d("Curr Version" , curVersion);
            Log.d("New Version" , newVersion);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

How to rename a file using Python

os.chdir(r"D:\Folder1\Folder2")
os.rename(src,dst)
#src and dst should be inside Folder2

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

  • Select-all in the designer file and delete everything in the file, leaving it blank and then save
  • Select-all in the ASPX/ASCX file and cut everything and then re-paste it back
  • The designer file should have regenerated the code

Windows Explorer "Command Prompt Here"

You can edit the registry to add the Command Prompt item to the context menu. Here are a couple of .reg files that I use.

Cmdhere.reg - for WinNT/2000/XP/Vista/7:

Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\shell\OpenNew]
@="Command Prompt"
[HKEY_CLASSES_ROOT\Directory\shell\OpenNew\Command]
@="cmd.exe /k cd %1"
[HKEY_CLASSES_ROOT\Drive\shell\OpenNew]
@="Command Prompt"
[HKEY_CLASSES_ROOT\Drive\shell\OpenNew\Command]
@="cmd.exe /k cd %1"

Doshere.reg - for Win9x:

REGEDIT4
[HKEY_CLASSES_ROOT\Directory\shell\OpenNew]
@="MS-DOS Prompt"
[HKEY_CLASSES_ROOT\Directory\shell\OpenNew\Command]
@="command.com /k cd %1"
[HKEY_CLASSES_ROOT\Drive\shell\OpenNew]
@="MS-DOS Prompt"
[HKEY_CLASSES_ROOT\Drive\shell\OpenNew\Command]
@="command.com /k cd %1"

Copy this into an empty text file and change the extension to .reg. Double-clicking on this in Windows Explorer will add these key to the registry.

Batchfile to create backup and rename with timestamp

Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.

You can also run your batch script through a vbs script like this:

'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True

This will execute your batch file with no cmd window shown.

How do I return a string from a regex match in python?

Note that re.match(pattern, string, flags=0) only returns matches at the beginning of the string. If you want to locate a match anywhere in the string, use re.search(pattern, string, flags=0) instead (https://docs.python.org/3/library/re.html). This will scan the string and return the first match object. Then you can extract the matching string with match_object.group(0) as the folks suggested.

Add Foreign Key relationship between two Databases

In my experience, the best way to handle this when the primary authoritative source of information for two tables which are related has to be in two separate databases is to sync a copy of the table from the primary location to the secondary location (using T-SQL or SSIS with appropriate error checking - you cannot truncate and repopulate a table while it has a foreign key reference, so there are a few ways to skin the cat on the table updating).

Then add a traditional FK relationship in the second location to the table which is effectively a read-only copy.

You can use a trigger or scheduled job in the primary location to keep the copy updated.

What does "exited with code 9009" mean during this build?

For me, disk space was low, and files that couldn't be written were expected to be present later. Other answers mentioned missing files (or misnamed/improperly referenced-by-name files)--but the root cause was lack of disk space.

SQL Server - How to lock a table until a stored procedure finishes

BEGIN TRANSACTION

select top 1 *
from table1
with (tablock, holdlock)

-- You do lots of things here

COMMIT

This will hold the 'table lock' until the end of your current "transaction".

How to set or change the default Java (JDK) version on OS X?

If you have multiple versions and you want to run something by using a specific version, use this example:

/usr/libexec/java_home -v 1.7.0_75 --exec java -jar you-file.jar

Can one do a for each loop in java in reverse order?

You'd need to reverse your collection if you want to use the for each syntax out of the box and go in reverse order.

How to render an ASP.NET MVC view as a string?

Additional tip for ASP NET CORE:

Interface:

public interface IViewRenderer
{
  Task<string> RenderAsync<TModel>(Controller controller, string name, TModel model);
}

Implementation:

public class ViewRenderer : IViewRenderer
{
  private readonly IRazorViewEngine viewEngine;

  public ViewRenderer(IRazorViewEngine viewEngine) => this.viewEngine = viewEngine;

  public async Task<string> RenderAsync<TModel>(Controller controller, string name, TModel model)
  {
    ViewEngineResult viewEngineResult = this.viewEngine.FindView(controller.ControllerContext, name, false);

    if (!viewEngineResult.Success)
    {
      throw new InvalidOperationException(string.Format("Could not find view: {0}", name));
    }

    IView view = viewEngineResult.View;
    controller.ViewData.Model = model;

    await using var writer = new StringWriter();
    var viewContext = new ViewContext(
       controller.ControllerContext,
       view,
       controller.ViewData,
       controller.TempData,
       writer,
       new HtmlHelperOptions());

       await view.RenderAsync(viewContext);

       return writer.ToString();
  }
}

Registration in Startup.cs

...
 services.AddSingleton<IViewRenderer, ViewRenderer>();
...

And usage in controller:

public MyController: Controller
{
  private readonly IViewRenderer renderer;
  public MyController(IViewRendere renderer) => this.renderer = renderer;
  public async Task<IActionResult> MyViewTest
  {
    var view = await this.renderer.RenderAsync(this, "MyView", model);
    return new OkObjectResult(view);
  }
}

How to set a variable inside a loop for /F

I struggeld for many hours on this. This is my loop to register command line vars. Example : Register.bat /param1:value1 /param2:value2

What is does, is loop all the commandline params, and that set the variable with the proper name to the value.

After that, you can just use set value=!param1! set value2=!param2!

regardless the sequence the params are given. (so called named parameters). Note the !<>!, instead of the %<>%.

SETLOCAL ENABLEDELAYEDEXPANSION

FOR %%P IN (%*) DO (
    call :processParam %%P
)

goto:End

:processParam [%1 - param]

    @echo "processparam : %1"
    FOR /F "tokens=1,2 delims=:" %%G IN ("%1") DO (
        @echo a,b %%G %%H
        set nameWithSlash=%%G
        set name=!nameWithSlash:~1!
        @echo n=!name!
        set value=%%H
        set !name!=!value!
    )
    goto :eof

:End    

How to grep a text file which contains some binary data?

You can also try Word Extractor tool. Word Extractor can be used with any file in your computer to separate the strings that contain human text / words from binary code (exe applications, DLLs).

Should I use scipy.pi, numpy.pi, or math.pi?

>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True

So it doesn't matter, they are all the same value.

The only reason all three modules provide a pi value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.

How to remove default mouse-over effect on WPF buttons?

This is similar to the solution referred by Mark Heath but with not as much code to just create a very basic button, without the built-in mouse over animation effect. It preserves a simple mouse over effect of showing the button border in black.

The style can be inserted into the Window.Resources or UserControl.Resources section for example (as shown).

<UserControl.Resources>
    <!-- This style is used for buttons, to remove the WPF default 'animated' mouse over effect -->
    <Style x:Key="MyButtonStyle" TargetType="Button">
        <Setter Property="OverridesDefaultStyle" Value="True"/>
        <Setter Property="Margin" Value="5"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Name="border" 
                        BorderThickness="1"
                        Padding="4,2" 
                        BorderBrush="DarkGray" 
                        CornerRadius="3" 
                        Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="border" Property="BorderBrush" Value="Black" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</UserControl.Resources>

<!-- usage in xaml -->
<Button Style="{StaticResource MyButtonStyle}">Hello!</Button>

How to start new activity on button click

The way to start new activities is to broadcast an intent, and there is a specific kind of intent that you can use to pass data from one activity to another. My recommendation is that you check out the Android developer docs related to intents; it's a wealth of info on the subject, and has examples too.

How to convert a string to utf-8 in Python

city = 'Ribeir\xc3\xa3o Preto'
print city.decode('cp1252').encode('utf-8')

How to control size of list-style-type disc in CSS?

You can also use 2D transform. It is illustrated in the snippet below with a list being scaled by 25%.

Nota: Bootstrap is used here for the sole purpose of layouting the demo (before/after effect).


_x000D_
_x000D_
ul#before {_x000D_
}_x000D_
_x000D_
ul#after {_x000D_
  transform: scale(1.25);_x000D_
}_x000D_
_x000D_
div.container, div.row {_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  border: 6px solid #000000;_x000D_
}
_x000D_
<!-- Bootstrap CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">_x000D_
_x000D_
<!-- Bootstrap theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">_x000D_
_x000D_
<!-- HTML -->_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-5">_x000D_
      Before_x000D_
    </div>_x000D_
    <div class="col-xs-5 col-xs-offset-1">_x000D_
      After (scale 25%)_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="row">_x000D_
    <div class="col-xs-5">_x000D_
      <ul id="before">_x000D_
        <li>Lorem ipsum dolor sit amet...</li>_x000D_
        <li>In vel ante vel est accumsan...</li>_x000D_
        <li>In elementum libero vel...</li>_x000D_
        <li>Nam ut ante a sem mattis...</li>_x000D_
        <li>Curabitur fermentum nisl...</li>_x000D_
        <li>Praesent vel risus ultrices...</li>_x000D_
      </ul>_x000D_
    </div>_x000D_
    <div class="col-xs-5 col-xs-offset-1">_x000D_
      <ul id="after">_x000D_
        <li>Lorem ipsum dolor sit amet...</li>_x000D_
        <li>In vel ante vel est accumsan...</li>_x000D_
        <li>In elementum libero vel...</li>_x000D_
        <li>Nam ut ante a sem mattis...</li>_x000D_
        <li>Curabitur fermentum nisl...</li>_x000D_
        <li>Praesent vel risus ultrices...</li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<!-- JQuery -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Bootstrap JS -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

Reference:

How to split a string into an array in Bash?

Another way would be:

string="Paris, France, Europe"
IFS=', ' arr=(${string})

Now your elements are stored in "arr" array. To iterate through the elements:

for i in ${arr[@]}; do echo $i; done

Quicksort: Choosing the pivot

On the average, Median of 3 is good for small n. Median of 5 is a bit better for larger n. The ninther, which is the "median of three medians of three" is even better for very large n.

The higher you go with sampling the better you get as n increases, but the improvement dramatically slows down as you increase the samples. And you incur the overhead of sampling and sorting samples.

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

sudo yum update openssl is all you need.

This will bring you up to openssl-1.0.1e-16.el6_5.7.

You need to restart Apache after the update. Or better yet, reboot the box if possible, so that all applications that use OpenSSL will load the new version.

OpenCV - Saving images to a particular folder of choice

Answer given by Jeru Luke is working only on Windows systems, if we try on another operating system (Ubuntu) then it runs without error but the image is saved on target location or path.

Not working in Ubuntu and working in Windows

  import cv2
  img = cv2.imread('1.jpg', 1)
  path = '/tmp'
  cv2.imwrite(str(path) + 'waka.jpg',img)
  cv2.waitKey(0)

I run above code but the image does not save the image on target path. Then I found that the way of adding path is wrong for the general purpose we using OS module to add the path.

Example:

 import os
 final_path = os.path.join(path_1,path_2,path_3......)

working in Ubuntu and Windows

 import cv2
 import os
 img = cv2.imread('1.jpg', 1)
 path = 'D:/OpenCV/Scripts/Images'
 cv2.imwrite(os.path.join(path , 'waka.jpg'),img)
 cv2.waitKey(0)

that code works fine on both Windows and Ubuntu :)

Adding item to Dictionary within loop

# Let's add key:value to a dictionary, the functional way 
# Create your dictionary class 
class my_dictionary(dict): 
    # __init__ function 
    def __init__(self): 
        self = dict()   
    # Function to add key:value 
    def add(self, key, value): 
        self[key] = value 
# Main Function 
dict_obj = my_dictionary() 
limit = int(input("Enter the no of key value pair in a dictionary"))
c=0
while c < limit :   
    dict_obj.key = input("Enter the key: ") 
    dict_obj.value = input("Enter the value: ") 
    dict_obj.add(dict_obj.key, dict_obj.value) 
    c += 1
print(dict_obj) 

How do I instantiate a JAXBElement<String> object?

When you imported the WSDL, you should have an ObjectFactory class which should have bunch of methods for creating various input parameters.

ObjectFactory factory = new ObjectFactory();
JAXBElement<String> createMessageDescription = factory.createMessageDescription("description");
message.setDescription(createMessageDescription);

Are multiple `.gitignore`s frowned on?

You can have multiple .gitignore, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore: git check-ignore -v -- afile.

And you can have different version of a .gitignore file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.

If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.


Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile in order to see which gitignore run (from which .gitignore file) is applied to 'yourfile', and better understand why said file is ignored.
See "which gitignore rule is ignoring my file?"

Android: how to handle button click

Option 1 and 2 involves using inner class that will make the code kind of clutter. Option 2 is sort of messy because there will be one listener for every button. If you have small number of button, this is okay. For option 4 I think this will be harder to debug as you will have to go back and fourth the xml and java code. I personally use option 3 when I have to handle multiple button clicks.

Python: Total sum of a list of numbers with the for loop

l = [1,2,3,4,5]
sum = 0
for x in l:
    sum = sum + x

And you can change l for any list you want.

Get ID from URL with jQuery

try this javascript

Snippet for getting the parameters from URL. Use javascript to get the URL parameters either from current window location or static URL into the argument for the function call.

javascript

function getUrlParameters(parameter, staticURL, decode){

       var currLocation = (staticURL.length)? staticURL : window.location.search,
           parArr = currLocation.split("?")[1].split("&"),
           returnBool = true;

       for(var i = 0; i < parArr.length; i++){
            parr = parArr[i].split("=");
            if(parr[0] == parameter){
                return (decode) ? decodeURIComponent(parr[1]) : parr[1];
                returnBool = true;
            }else{
                returnBool = false;            
            }
       }

       if(!returnBool) return false;  
    }

To get the parameter “id” from above static URL, use the following:

var idParameter = getUrlParameters("id", "http://www.example.com?id=1234&auth=true", true);

or

var idParameter = getUrlParameters("id", "", true);

Cannot make file java.io.IOException: No such file or directory

I got the same problem when using rest-easy. After searching while i figured that this error occured when there is no place to keep temporary files. So in tomcat you can just create tomcat-root/temp folder.

How to stop console from closing on exit?

You could open a command prompt, CD to the Debug or Release folder, and type the name of your exe. When I suggest this to people they think it is a lot of work, but here are the bare minimum clicks and keystrokes for this:

  • in Visual Studio, right click your project in Solution Explorer or the tab with the file name if you have a file in the solution open, and choose Open Containing Folder or Open in Windows Explorer
  • in the resulting Windows Explorer window, double-click your way to the folder with the exe
  • Shift-right-click in the background of the explorer window and choose Open Commmand Window here
  • type the first letter of your executable and press tab until the full name appears
  • press enter

I think that's 14 keystrokes and clicks (counting shift-right-click as two for example) which really isn't much. Once you have the command prompt, of course, running it again is just up-arrow, enter.

Undefined symbols for architecture armv7

Go TARGETS -> General -> Deployment Info -> set Target 8.1 or 10.0

Framework or Library have no ARMV7 Architecture.

JavaScript data grid for millions of rows

Here are a couple of optimizations you can apply you speed up things. Just thinking out loud.

Since the number of rows can be in the millions, you will want a caching system just for the JSON data from the server. I can't imagine anybody wanting to download all X million items, but if they did, it would be a problem. This little test on Chrome for an array on 20M+ integers crashes on my machine constantly.

var data = [];
for(var i = 0; i < 20000000; i++) {
    data.push(i);
}
console.log(data.length);?

You could use LRU or some other caching algorithm and have an upper bound on how much data you're willing to cache.

For the table cells themselves, I think constructing/destroying DOM nodes can be expensive. Instead, you could just pre-define X number of cells, and whenever the user scrolls to a new position, inject the JSON data into these cells. The scrollbar would virtually have no direct relationship to how much space (height) is required to represent the entire dataset. You could arbitrarily set the table container's height, say 5000px, and map that to the total number of rows. For example, if the containers height is 5000px and there are a total of 10M rows, then the starting row ˜ (scroll.top/5000) * 10M where scroll.top represents the scroll distance from the top of the container. Small demo here.

To detect when to request more data, ideally an object should act as a mediator that listens to scroll events. This object keeps track of how fast the user is scrolling, and when it looks like the user is slowing down or has completely stopped, makes a data request for the corresponding rows. Retrieving data in this fashion means your data is going to be fragmented, so the cache should be designed with that in mind.

Also the browser limits on maximum outgoing connections can play an important part. A user may scroll to a certain position which will fire an AJAX request, but before that finishes the user can scroll to some other portion. If the server is not responsive enough the requests would get queued up and the application will look unresponsive. You could use a request manager through which all requests are routed, and it can cancel pending requests to make space.

Calling a java method from c++ in Android

If it's an object method, you need to pass the object to CallObjectMethod:

jobject result = env->CallObjectMethod(obj, messageMe, jstr);

What you were doing was the equivalent of jstr.messageMe().

Since your is a void method, you should call:

env->CallVoidMethod(obj, messageMe, jstr);

If you want to return a result, you need to change your JNI signature (the ()V means a method of void return type) and also the return type in your Java code.

Splitting a table cell into two columns in HTML

You have two options.

  1. Use an extra column in the header, and use <colspan> in your header to stretch a cell for two or more columns.
  2. Insert a <table> with 2 columns inside the td you want extra columns in.

UnsatisfiedDependencyException: Error creating bean with name

I know it seems too late, but it may help others in future.

I face the same error and the problem was that spring boot did not read my services package so add:

@ComponentScan(basePackages = {"com.example.demo.Services"}) (you have to specify your own path to the services package) and in the class demoApplication (class that have main function) and for service interface must be annotated @Service and the class that implement the service interface must be annotated with @Component, then autowired the service interface.

How to force reloading a page when using browser back button?

An alternative that solved the problem to me is to disable cache for the page. That make the browser to get the page from the server instead of using a cached version:

Response.AppendHeader("Cache-Control","no-cache, no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache");
Response.AppendHeader("Expires", "0");

Spring not autowiring in unit tests with JUnit

I'm using JUnit 5 and for me the problem was that I had imported Test from the wrong package:

import org.junit.Test;

Replacing it with the following worked for me:

import org.junit.jupiter.api.Test;

How to automatically redirect HTTP to HTTPS on Apache servers?

for me this worked

RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

How to get the start time of a long-running Linux process?

As a follow-up to Adam Matan's answer, the /proc/<pid> directory's time stamp as such is not necessarily directly useful, but you can use

awk -v RS=')' 'END{print $20}' /proc/12345/stat

to get the start time in clock ticks since system boot.1

This is a slightly tricky unit to use; see also convert jiffies to seconds for details.

awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
    END { printf "%9.0f\n", now - ($20/ticks) }' /proc/uptime RS=')' /proc/12345/stat

This should give you seconds, which you can pass to strftime() to get a (human-readable, or otherwise) timestamp.

awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
    END { print strftime("%c", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/12345/stat

Updated with some fixes from Stephane Chazelas in the comments; thanks as always!

If you only have Mawk, maybe try

awk -v ticks="$(getconf CLK_TCK)" -v epoch="$(date +%s)" '
  NR==1 { now=$1; next }
  END { printf "%9.0f\n", epoch - (now-($20/ticks)) }' /proc/uptime RS=')' /proc/12345/stat |
xargs -i date -d @{}

1 man proc; search for starttime.

Split string on whitespace in Python

import re
s = "many   fancy word \nhello    \thi"
re.split('\s+', s)

Two Decimal places using c#

In some tests here, it worked perfectly this way:

Decimal.Round(value, 2);

Hope this helps

CSS selector for disabled input type="submit"

As said by jensgram, IE6 does not support attribute selector. You could add a class="disabled" to select the disabled inputs so that this can work in IE6.

How to create an empty file with Ansible?

The documentation of the file module says

If state=file, the file will NOT be created if it does not exist, see the copy or template module if you want that behavior.

So we use the copy module, using force=no to create a new empty file only when the file does not yet exist (if the file exists, its content is preserved).

- name: ensure file exists
  copy:
    content: ""
    dest: /etc/nologin
    force: no
    group: sys
    owner: root
    mode: 0555

This is a declarative and elegant solution.

How do I send a cross-domain POST request via JavaScript?

  1. Create two hidden iframes (add "display: none;" to the css style). Make your second iframe point to something on your own domain.

  2. Create a hidden form, set its method to "post" with target = your first iframe, and optionally set enctype to "multipart/form-data" (I'm thinking you want to do POST because you want to send multipart data like pictures?)

  3. When ready, make the form submit() the POST.

  4. If you can get the other domain to return javascript that will do Cross-Domain Communication With Iframes (http://softwareas.com/cross-domain-communication-with-iframes) then you are in luck, and you can capture the response as well.

Of course, if you want to use your server as a proxy, you can avoid all this. Simply submit the form to your own server, which will proxy the request to the other server (assuming the other server isn't set up to notice IP discrepancies), get the response, and return whatever you like.

QtCreator: No valid kits found

In my case the issue was that my default kit's Qt version was None.

Go to Tools -> Options... -> Build & Run -> Kits tab, click on the kit you want to make as default and you'll see a list of fields beneath, one of which is Qt version. If it's None, change it to one of the versions available to you in the Qt versions tab which is just next to the Kits tab.

Format timedelta to string

def td_format(td_object):
    seconds = int(td_object.total_seconds())
    periods = [
        ('year',        60*60*24*365),
        ('month',       60*60*24*30),
        ('day',         60*60*24),
        ('hour',        60*60),
        ('minute',      60),
        ('second',      1)
    ]

    strings=[]
    for period_name, period_seconds in periods:
        if seconds > period_seconds:
            period_value , seconds = divmod(seconds, period_seconds)
            has_s = 's' if period_value > 1 else ''
            strings.append("%s %s%s" % (period_value, period_name, has_s))

    return ", ".join(strings)

Programmatically Creating UILabel

Swift 3:

let label = UILabel(frame: CGRect(x:0,y: 0,width: 250,height: 50))
label.textAlignment = .center
label.textColor = .white
label.font = UIFont(name: "Avenir-Light", size: 15.0)
label.text = "This is a Label"
self.view.addSubview(label)

curl: (6) Could not resolve host: google.com; Name or service not known

Perhaps you have some very weird and restrictive SELinux rules in place?

If not, try strace -o /tmp/wtf -fF curl -v google.com and try to spot from /tmp/wtf output file what's going on.

Codeigniter: does $this->db->last_query(); execute a query?

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

Definition of a Balanced Tree

There are several ways to define "Balanced". The main goal is to keep the depths of all nodes to be O(log(n)).

It appears to me that the balance condition you were talking about is for AVL tree.
Here is the formal definition of AVL tree's balance condition:

For any node in AVL, the height of its left subtree differs by at most 1 from the height of its right subtree.

Next question, what is "height"?

The "height" of a node in a binary tree is the length of the longest path from that node to a leaf.

There is one weird but common case:

People define the height of an empty tree to be (-1).

For example, root's left child is null:

              A  (Height = 2)
           /     \
(height =-1)       B (Height = 1) <-- Unbalanced because 1-(-1)=2 >1
                    \
                     C (Height = 0)

Two more examples to determine:

Yes, A Balanced Tree Example:

        A (h=3)
     /     \
 B(h=1)     C (h=2)        
/          /   \
D (h=0)  E(h=0)  F (h=1)
               /
              G (h=0)

No, Not A Balanced Tree Example:

        A (h=3)
     /     \
 B(h=0)     C (h=2)        <-- Unbalanced: 2-0 =2 > 1
           /   \
        E(h=1)  F (h=0)
        /     \
      H (h=0)   G (h=0)      

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

How do I clone a Django model instance object and save it to the database?

To clone a model with multiple inheritance levels, i.e. >= 2, or ModelC below

class ModelA(models.Model):
    info1 = models.CharField(max_length=64)

class ModelB(ModelA):
    info2 = models.CharField(max_length=64)

class ModelC(ModelB):
    info3 = models.CharField(max_length=64)

Please refer the question here.

How to get WooCommerce order details

WOOCOMMERCE ORDERS IN VERSION 3.0+

Since Woocommerce mega major Update 3.0+ things have changed quite a lot:

Related:
How to get Customer details from Order in WooCommerce?
Get Order items and WC_Order_Item_Product in WooCommerce 3

So the Order items properties will not be accessible as before in a foreach loop and you will have to use these specific getter and setter methods instead.

Using some WC_Order and WC_Abstract_Order methods (example):

// Get an instance of the WC_Order object (same as before)
$order = wc_get_order( $order_id );

$order_id  = $order->get_id(); // Get the order ID
$parent_id = $order->get_parent_id(); // Get the parent order ID (for subscriptions…)

$user_id   = $order->get_user_id(); // Get the costumer ID
$user      = $order->get_user(); // Get the WP_User object

$order_status  = $order->get_status(); // Get the order status (see the conditional method has_status() below)
$currency      = $order->get_currency(); // Get the currency used  
$payment_method = $order->get_payment_method(); // Get the payment method ID
$payment_title = $order->get_payment_method_title(); // Get the payment method title
$date_created  = $order->get_date_created(); // Get date created (WC_DateTime object)
$date_modified = $order->get_date_modified(); // Get date modified (WC_DateTime object)

$billing_country = $order->get_billing_country(); // Customer billing country

// ... and so on ...

For order status as a conditional method (where "the_targeted_status" need to be defined and replaced by an order status to target a specific order status):

if ( $order->has_status('completed') ) {
    // Do something
}

Get and access to the order data properties (in an array of values):

// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );

$order_data = $order->get_data(); // The Order data

$order_id = $order_data['id'];
$order_parent_id = $order_data['parent_id'];
$order_status = $order_data['status'];
$order_currency = $order_data['currency'];
$order_version = $order_data['version'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method_title = $order_data['payment_method_title'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method = $order_data['payment_method'];

## Creation and modified WC_DateTime Object date string ##

// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');

// Using a timestamp ( with php getTimestamp() function as method)
$order_timestamp_created = $order_data['date_created']->getTimestamp();
$order_timestamp_modified = $order_data['date_modified']->getTimestamp();

$order_discount_total = $order_data['discount_total'];
$order_discount_tax = $order_data['discount_tax'];
$order_shipping_total = $order_data['shipping_total'];
$order_shipping_tax = $order_data['shipping_tax'];
$order_total = $order_data['total'];
$order_total_tax = $order_data['total_tax'];
$order_customer_id = $order_data['customer_id']; // ... and so on

## BILLING INFORMATION:

$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_company = $order_data['billing']['company'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];

## SHIPPING INFORMATION:

$order_shipping_first_name = $order_data['shipping']['first_name'];
$order_shipping_last_name = $order_data['shipping']['last_name'];
$order_shipping_company = $order_data['shipping']['company'];
$order_shipping_address_1 = $order_data['shipping']['address_1'];
$order_shipping_address_2 = $order_data['shipping']['address_2'];
$order_shipping_city = $order_data['shipping']['city'];
$order_shipping_state = $order_data['shipping']['state'];
$order_shipping_postcode = $order_data['shipping']['postcode'];
$order_shipping_country = $order_data['shipping']['country'];

Get the order items and access the data with WC_Order_Item_Product and WC_Order_Item methods:

// Get an instance of the WC_Order object
$order = wc_get_order($order_id);

// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item ):

    ## Using WC_Order_Item methods ##

    // Item ID is directly accessible from the $item_key in the foreach loop or
    $item_id = $item->get_id();

    ## Using WC_Order_Item_Product methods ##

    $product      = $item->get_product(); // Get the WC_Product object

    $product_id   = $item->get_product_id(); // the Product id
    $variation_id = $item->get_variation_id(); // the Variation id

    $item_type    = $item->get_type(); // Type of the order item ("line_item")

    $item_name    = $item->get_name(); // Name of the product
    $quantity     = $item->get_quantity();  
    $tax_class    = $item->get_tax_class();
    $line_subtotal     = $item->get_subtotal(); // Line subtotal (non discounted)
    $line_subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax (non discounted)
    $line_total        = $item->get_total(); // Line total (discounted)
    $line_total_tax    = $item->get_total_tax(); // Line total tax (discounted)

    ## Access Order Items data properties (in an array of values) ##
    $item_data    = $item->get_data();

    $product_name = $item_data['name'];
    $product_id   = $item_data['product_id'];
    $variation_id = $item_data['variation_id'];
    $quantity     = $item_data['quantity'];
    $tax_class    = $item_data['tax_class'];
    $line_subtotal     = $item_data['subtotal'];
    $line_subtotal_tax = $item_data['subtotal_tax'];
    $line_total        = $item_data['total'];
    $line_total_tax    = $item_data['total_tax'];

    // Get data from The WC_product object using methods (examples)
    $product        = $item->get_product(); // Get the WC_Product object

    $product_type   = $product->get_type();
    $product_sku    = $product->get_sku();
    $product_price  = $product->get_price();
    $stock_quantity = $product->get_stock_quantity();

endforeach;

So using get_data() method allow us to access to the protected data (associative array mode) …

wp_nav_menu change sub-menu class name?

Here's an update to what Richard did that adds a "depth" indicator. The output is level-0, level-1, level-2, etc.

class UL_Class_Walker extends Walker_Nav_Menu {
  function start_lvl(&$output, $depth) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class=\"level-".$depth."\">\n";
  }
}

Installing SciPy and NumPy using pip

in my case, upgrading pip did the trick. Also, I've installed scipy with -U parameter (upgrade all packages to the last available version)

Convert UTC/GMT time to local time

@TimeZoneInfo.ConvertTimeFromUtc(timeUtc, TimeZoneInfo.Local)

How to display raw html code in PRE or something like it but without escaping it

Essentially the original question can be broken down in 2 parts:

  • Main objective/challenge: embedding(/transporting) a raw formatted code-snippet (any kind of code) in a web-page's markup (for simple copy/paste/edit due to no encoding/escaping)
  • correctly displaying/rendering that code-snippet (possibly edit it) in the browser

The short (but) ambiguous answer is: you can't, ...but you can (get very close).
(I know, that are 3 contradicting answers, so read on...)

(polyglot)(x)(ht)ml Markup-languages rely on wrapping (almost) everything between begin/opening and end/closing tags/character(sequences).
So, to embed any kind of raw code/snippet inside your markup-language, one will always have to escape/encode every instance (inside that snippet) that resembles the character(-sequence) that would close the wrapping 'container' element in the markup. (During this post I'll refer to this as rule no 1.)
Think of "some "data" here" or <i>..close italics with '</i>'-tag</i>, where it is obvious one should escape/encode (something in) </i and " (or change container's quote-character from " to ').

So, because of rule no 1, you can't 'just' embed 'any' unknown raw code-snippet inside markup.
Because, if one has to escape/encode even one character inside the raw snippet, then that snippet would no longer be the same original 'pure raw code' that anyone can copy/paste/edit in the document's markup without further thought. It would lead to malformed/illegal markup and Mojibake (mainly) because of entities.
Also, should that snippet contain such characters, you'd still need some javascript to 'translate' that character(sequence) from (and to) it's escaped/encoded representation to display the snippet correctly in the 'webpage' (for copy/paste/edit).

That brings us to (some of) the datatypes that markup-languages specify. These datatypes essentially define what are considered 'valid characters' and their meaning (per tag, property, etc.):

  • PCDATA (Parsed Character DATA): will expand entities and one must escape <, & (and > depending on markup language/version).
    Most tags like body, div, pre, etc, but also textarea (until HTML5) fall under this type.
    So not only do you need to encode all the container's closing character-sequences inside the snippet, you also have to encode all <, & (,>) characters (at minimum).
    Needless to say, encoding/escaping this many characters falls outside this objective's scope of embedding a raw snippet in the markup.
    '..But a textarea seems to work...', yes, either because of the browsers error-engine trying to make something out of it, or because HTML5:

  • RCDATA (Replaceable Character DATA): will not not treat tags inside the text as markup (but are still governed by rule 1), so one doesn't need to encode < (>). BUT entities are still expanded, so they and 'ambiguous ampersands' (&) need special care.
    The current HTML5 spec says the textarea is now a RCDATA field and (quote):

    The text in raw text and RCDATA elements must not contain any occurrences of the string "</" (U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).

    Thus no matter what, textarea needs a hefty entity translation handler or it will eventually Mojibake on entities!

  • CDATA (Character Data) will not treat tags inside the text as markup and will not expand entities.
    So as long as the raw snippet code does not violate rule 1 (that one can't have the containers closing character(sequence) inside the snippet), this requires no other escaping/encoding.

Clearly this boils down to: how can we minimize the number of characters/character-sequences that still need to be encoded in the snippet's raw source and the number of times that character(sequence) might appear in an average snippet; something that is also of importance for the javascript that handles the translation of these characters (if they occur).

So what 'containers' have this CDATA context?

Most value properties of tags are CDATA, so one could (ab)use a hidden input's value property (proof of concept jsfiddle here).
However (conform rule 1) this creates an encoding/escape problem with nested quotes (" and ') in the raw snippet and one needs some javascript to get/translate and set the snippet in another (visible) element (or simply setting it as a text-area's value). Somehow this gave me problems with entities in FF (just like in a textarea). But it doesn't really matter, since the 'price' of having to escape/encode nested quotes is higher then a (HTML5) textarea (quotes are quite common in source code..).

What about trying to (ab)use <![CDATA[<tag>bla & bla</tag>]]>?
As Jukka points out in his extended answer, this would only work in (rare) 'real xhtml'.
I thought of using a script-tag (with or without such a CDATA wrapper inside the script-tag) together with a multi-line comment /* */ that wraps the raw snippet (script-tags can have an id and you can access them by count). But since this obviously introduces a escaping problem with */, ]]> and </script in the raw snippet, this doesn't seem like a solution either.

Please post other viable 'containers' in the comments to this answer.

By the way, encoding or counting the number of - characters and balancing them out inside a comment tag <!-- --> is just insane for this purpose (apart from rule 1).


That leaves us with Jukka K. Korpela's excellent answer: the <xmp> tag seems the best option!

The 'forgotten' <xmp> holds CDATA, is intended for this purpose AND is indeed still in the current HTML 5 spec (and has been at least since HTML3.2); exactly what we need! It's also widely supported, even in IE6 (that is.. until it suffers from the same regression as the scrolling table-body).
Note: as Jukka pointed out, this will not work in true xhtml or polyglot (that will treat it as a pre) and the xmp tag must still adhere to rule no 1. But that's the 'only' rule.

Consider the following markup:

<!-- ATTENTION: replace any occurrence of &lt;/xmp with </xmp -->
<xmp id="snippet-container">
<div>
    <div>this is an example div &amp; holds an xmp tag:<br />
        <xmp> 
<html><head>  <!-- indentation col 0!! -->
    <title>My Title</title>
</head><body>
    <p>hello world !!</p>
</body></html>
        &lt;/xmp>  <!-- note this encoded/escaped tag -->
    </div>
    This line is also part of the snippet
</div>
</xmp>

The above codeblok illustrates a raw piece of markup where <xmp id="snippet-container"> contains an (almost raw) code-snippet (containing div>div>xmp>html-document).
Notice the encoded closing tag in this markup? To comply with rule no 1, this was encoded/escaped).

So embedding/transporting the (sometimes almost) raw code is/seems solved.

What about displaying/rendering the snippet (and that encoded &lt;/xmp>)?

The browser will (or it should) render the snippet (the contents inside snippet-container) exactly the way you see it in the codeblock above (with some discrepancy amongst browsers whether or not the snippet starts with a blank line).
That includes the formatting/indentation, entities (like the string &amp;), full tags, comments AND the encoded closing tag &lt;/xmp> (just like it was encoded in the markup). And depending on browser(version) one could even try use the property contenteditable="true" to edit this snippet (all that without javascript enabled). Doing something like textarea.value=xmp.innerHTML is also a breeze.

So you can... if the snippet doesn't contain the containers closing character-sequence.

However, should a raw snippet contain the closing character-sequence </xmp (because it is an example of xmp itself or it contains some regex, etc), you must accept that you have to encode/escape that sequence in the raw snippet AND need a javascript handler to translate that encoding to display/render the encoded &lt;/xmp> like </xmp> inside a textarea (for editing/posting) or (for example) a pre just to correctly render the snippet's code (or so it seems).

A very rudimentary jsfiddle example of this here. Note that getting/embedding/displaying/retrieving-to-textarea worked perfect even in IE6. But setting the xmp's innerHTML revealed some interesting 'would-be-intelligent' behavior on IE's part. There is a more extensive note and workaround on that in the fiddle.

But now comes the important kicker (another reason why you only get very close): Just as an over-simplified example, imagine this rabbit-hole:

Intended raw code-snippet:

<!-- remember to translate between </xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Well, to comply with rule 1, we 'only' need to encode those </xmp[> \n\r\t\f\/] sequences, right?

So that gives us the following markup (using just a possible encoding):

<xmp id="container">
<!-- remember to translate between &lt;/xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
&lt;/xmp>
</xmp>

Hmm.. shalt I get my crystal ball or flip a coin? No, let the computer look at its system-clock and state that a derived number is 'random'. Yes, that should do it..

Using a regex like: xmp.innerHTML.replace(/&lt;(?=\/xmp[> \n\r\t\f\/])/gi, '<');, would translate 'back' to this:

<!-- remember to translate between </xmp> and </xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Hmm.. seems this random generator is broken... Houston..?
Should you have missed the joke/problem, read again starting at the 'intended raw code-snippet'.

Wait, I know, we (also) need to encode .... to ....
Ok, rewind to 'intended raw code-snippet' and read again.
Somehow this all begins to smell like the famous hilarious-but-true rexgex-answer on SO, a good read for people fluent in mojibake.

Maybe someone knows a clever algorithm or solution to fix this problem, but I assume that the embedded raw code will get more and more obscure to the point where you'd be better of properly escaping/encoding just your <, & (and >), just like the rest of the world.

Conclusion: (using the xmp tag)

  • it can be done with known snippets that do not contain the container's closing character-sequence,
  • we can get very close to the original objective with known snippets that only use 'basic first-level' escaping/encoding so we don't fall in the rabbithole,
  • but ultimately it seems that one can't do this reliably in a 'production-environment' where people can/should copy/paste/edit 'any unknown' raw snippets while not knowing/understanding the implications/rules/rabbithole (depending on your implementation of handling/translating for rule 1 and the rabbit-hole).

Hope this helps!

PS: Whilst I would appreciate an upvote if you find this explanation useful, I kind of think Jukka's answer should be the accepted answer (should no better option/answer come along), since he was the one who remembered the xmp tag (that I forgot about over the years and got 'distracted' by the commonly advocated PCDATA elements like pre, textarea, etc.).
This answer originated in explaining why you can't do it (with any unknown raw snippet) and explain some obvious pitfalls that some other (now deleted) answers overlooked when advising a textarea for embedding/transport. I've expanded my existing explanation to also support and further explain Jukka's answer (since all that entity and *CDATA stuff is almost harder than code-pages).

Angular - How to apply [ngStyle] conditions

<ion-col size="12">
  <ion-card class="box-shadow ion-text-center background-size"
  *ngIf="data != null"
  [ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">

  </ion-card>

Test iOS app on device without apple developer program or jailbreak

It's worth the buck to apply for the Apple developer program. You will be able to use ad-hoc provisioning to distribute your app to testers and test devices. You're allowed to add 100 ad-hoc provisioning devices to your developer program.

Calling Scalar-valued Functions in SQL

Make sure you have the correct database selected. You may have the master database selected if you are trying to run it in a new query window.

How do I align a label and a textarea?

  1. Set the height of your label to the same height as the multiline textbox.
  2. Add the cssClass .alignTop{vertical-align: middle;} for the label control.

    <p>
        <asp:Label ID="DescriptionLabel" runat="server" Text="Description: " Width="70px" Height="200px" CssClass="alignTop"></asp:Label>
        <asp:Textbox id="DescriptionTextbox" runat="server" Width="400px" Height="200px" TextMode="MultiLine"></asp:Textbox>
        <asp:RequiredFieldValidator id="DescriptionRequiredFieldValidator" runat="server" ForeColor="Red"
        ControlToValidate="DescriptionTextbox" ErrorMessage="Description is a required field.">    
    </asp:RequiredFieldValidator>
    

How to dismiss a Twitter Bootstrap popover by clicking outside?

Modified accepted solution. What I've experienced was that after some popovers were hidden, they would have to be clicked twice to show up again. Here's what I did to ensure that popover('hide') wasn't being called on already hidden popovers.

$('body').on('click', function (e) {
    $('[data-original-title]').each(function () {
        //the 'is' for buttons that trigger popups
        //the 'has' for icons within a button that triggers a popup
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            var popoverElement = $(this).data('bs.popover').tip();
            var popoverWasVisible = popoverElement.is(':visible');

            if (popoverWasVisible) {
                $(this).popover('hide');
                $(this).click(); // double clicking required to reshow the popover if it was open, so perform one click now
            }
        }
    });
});

Creating a new user and password with Ansible

I want to propose yet another solution:

- name: Create madhead user
  user:
    name: madhead
    password: "{{ 'password' | password_hash('sha512') }}"
    shell: /bin/zsh
    update_password: on_create
  register: madhead
- name: Force madhead to change password
  shell: chage -d 0 madhead
  when: madhead.changed

Why it is better? Like already has been noted here, Ansible plays should be idempotent. You should think of them not as a sequence of actions in imperative style, but like a desired state, declarative style. As a result you should be able to run it multiple times and get the same result, the same server state.

This all sounds great, but there are some nuances. One of them is managing users. "Desired state" means that every time you run a play that creates a user he will be updated to match exactly that state. By "updated" I mean that his password will be changed too. But most probably it is not what you need. Usually, you need to create user, set and expire his password only once, further play runs shouldn't update his password.

Fortunately, Ansible has update_password attribute in user module that solves this issue. Mixing this with registered variables you can also expire his password only when the user is actually updated.

Note that if you change user's shell manually (suppose, you don't like the shell that evil admin forced in his play) the user will be updated, thus his password will be expired.

Also note how you can easily use plain text initial passwords in plays. No need to encode them somewhere else and paste hashes, you can use Jinja2 filter for that. However, this can be a security flaw if someone happens to login before you initially do.

git checkout master error: the following untracked working tree files would be overwritten by checkout

do a :

git branch

if git show you something like :

* (no branch)
master
Dbranch

You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with

git checkout master 

Now you should be able to delete the Dbranch.

How to rename a table column in Oracle 10g

suppose supply_master is a table, and

SQL>desc supply_master;


SQL>Name
 SUPPLIER_NO    
 SUPPLIER_NAME
 ADDRESS1       
 ADDRESS2       
 CITY           
 STATE          
 PINCODE  


SQL>alter table Supply_master rename column ADDRESS1 TO ADDR;
Table altered



SQL> desc Supply_master;
 Name                   
 -----------------------
 SUPPLIER_NO            
 SUPPLIER_NAME          
 ADDR   ///////////this has been renamed........//////////////                
 ADDRESS2               
 CITY                   
 STATE                  
 PINCODE                  

In Unix, how do you remove everything in the current directory and below it?

What I always do is type

rm -rf *

and then hit ESC-*, and bash will expand the * to an explicit list of files and directories in the current working directory.

The benefits are:

  • I can review the list of files to delete before hitting ENTER.
  • The command history will not contain "rm -rf *" with the wildcard intact, which might then be accidentally reused in the wrong place at the wrong time. Instead, the command history will have the actual file names in there.
  • It has also become handy once or twice to answer "wait a second... which files did I just delete?". The file names are visible in the terminal scrollback buffer or the command history.

In fact, I like this so much that I've made it the default behavior for TAB with this line in .bashrc:

bind TAB:insert-completions

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

com.android.build.transform.api.TransformException

you can see the documentation of Android

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.0"

    defaultConfig {
        ...
        minSdkVersion 14
        targetSdkVersion 21
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.0'
}

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

Is it possible to capture the stdout from the sh DSL command in the pipeline

I had the same issue and tried almost everything then found after I came to know I was trying it in the wrong block. I was trying it in steps block whereas it needs to be in the environment block.

        stage('Release') {
                    environment {
                            my_var = sh(script: "/bin/bash ${assign_version} || ls ", , returnStdout: true).trim()
                                }
                    steps {                                 
                            println my_var
                            }
                }

How do I compare two Integers?

I would go with x.equals(y) because that's consistent way to check equality for all classes.

As far as performance goes, equals is actually more expensive because it ends up calling intValue().

EDIT: You should avoid autoboxing in most cases. It can get really confusing, especially the author doesn't know what he was doing. You can try this code and you will be surprised by the result;

Integer a = 128;
Integer b = 128;

System.out.println(a==b);

How to make vim paste from (and copy to) system's clipboard?

A quick note for people whose vim installation does not support the * and + registers. It is not necessary to download a new vim installation to paste from the clipboard. Here is an alternative method:

1) Install parcellite (a clipboard manager with a low memory footprint);

2) In your .vimrc file, add the following:

command Clip r !parcellite -c

3) Restart vim.

Now when you type in :Clip as an ex command, the contents of the clipboard will be pasted in at the cursor. You can also map the new command to a function key so as to be able to do this with one keystroke.

How to clear PermGen space Error in tomcat

If tomcat is running as Windows Service neither CATALINA_OPTS nor JAVA_OPTS seems to have any effect.

You need to set it in Java options in GUI.

The below link explains it well

http://www.12robots.com/index.cfm/2010/10/8/Giving-more-memory-to-the-Tomcat-Service-in-Windows

How do I check if there are duplicates in a flat list?

Another way of doing this succinctly is with Counter.

To just determine if there are any duplicates in the original list:

from collections import Counter

def has_dupes(l):
    # second element of the tuple has number of repetitions
    return Counter(l).most_common()[0][1] > 1

Or to get a list of items that have duplicates:

def get_dupes(l):
    return [k for k, v in Counter(l).items() if v > 1]

Remove scrollbar from iframe

If anyone here is having a problem with disabling scrollbars on the iframe, it could be because the iframe's content has scrollbars on elements below the html element!

Some layouts set html and body to 100% height, and use a #wrapper div with overflow: auto; (or scroll), thereby moving the scrolling to the #wrapper element.

In such a case, nothing you do will prevent the scrollbars from showing up except editing the other page's content.

Cause of a process being a deadlock victim

Q1:Could the time it takes for a transaction to execute make the associated process more likely to be flagged as a deadlock victim.

No. The SELECT is the victim because it had only read data, therefore the transaction has a lower cost associated with it so is chosen as the victim:

By default, the Database Engine chooses as the deadlock victim the session running the transaction that is least expensive to roll back. Alternatively, a user can specify the priority of sessions in a deadlock situation using the SET DEADLOCK_PRIORITY statement. DEADLOCK_PRIORITY can be set to LOW, NORMAL, or HIGH, or alternatively can be set to any integer value in the range (-10 to 10).

Q2. If I execute the select with a NOLOCK hint, will this remove the problem?

No. For several reasons:

Q3. I suspect that a datetime field that is checked as part of the WHERE clause in the select statement is causing the slow lookup time. Can I create an index based on this field? Is it advisable?

Probably. The cause of the deadlock is almost very likely to be a poorly indexed database.10 minutes queries are acceptable in such narrow conditions, that I'm 100% certain in your case is not acceptable.

With 99% confidence I declare that your deadlock is cased by a large table scan conflicting with updates. Start by capturing the deadlock graph to analyze the cause. You will very likely have to optimize the schema of your database. Before you do any modification, read this topic Designing Indexes and the sub-articles.

How to check what version of jQuery is loaded?

// My original 'goto' means to get the version
$.fn.jquery

// Another *similar* option
$().jQuery

// If there is concern that there may be multiple implementations of `$` then:
jQuery.fn.jquery

Recently I have had issues using $.fn.jquery/$().jQuery on a few sites so I wanted to note a third simple command to pull the jQuery version.

If you get back a version number -- usually as a string -- then jQuery is loaded and that is what version you're working with. If not loaded then you should get back undefined or maybe even an error.

Pretty old question and I've seen a few people that have already mentioned my answer in comments. However, I find that sometimes great answers that are left as comments can go unnoticed; especially when there are a lot of comments to an answer you may find yourself digging through piles of them looking for a gem. Hopefully this helps someone out!

Split text with '\r\n'

The problem is not with the splitting but rather with the WriteLine. A \n in a string printed with WriteLine will produce an "extra" line.

Example

var text = 
  "somet interesting text\n" +
  "some text that should be in the same line\r\n" +
  "some text should be in another line";

string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine("Nr. Of items in list: " + lines.Length); // 2 lines
foreach (string s in lines)
{
   Console.WriteLine(s); //But will print 3 lines in total.
}

To fix the problem remove \n before you print the string.

Console.WriteLine(s.Replace("\n", ""));

How to preview git-pull without doing fetch?

I created a custom git alias to do that for me:

alias.changes=!git log --name-status HEAD..

with that you can do this:

$git fetch
$git changes origin

This will get you a nice and easy way to preview changes before doing a merge.

How do I generate random number for each row in a TSQL Select?

If you want to generate a random number between 1 and 14 inclusive.

SELECT CONVERT(int, RAND() * (14 - 1) + 1)

OR

SELECT ABS(CHECKSUM(NewId())) % (14 -1) + 1

How do you get the current page number of a ViewPager for Android?

There is a method object_of_ViewPager.getCurrentItem() which returns the position of currently Viewed page of view pager

failed to load ad : 3

I've made the stupidest error. Passed app id into MobileAds.initialize from one app and used placement id in loadAd from another admob app.

Once I corrected placement id all come to work.

How to change the name of an iOS app?

I am using this script after I rename my iOS Project. It helps to change the directories name and make the names in sync.

http://github.com/ytbryan/rename

NOTE: you will need to manually change the scheme's name.

How do you launch the JavaScript debugger in Google Chrome?

The most efficient way I have found to get to the javascript debugger is by running this:

chrome://inspect

Fill remaining vertical space with CSS using display:flex

A more modern approach would be to use the grid property.

_x000D_
_x000D_
section {_x000D_
  display: grid;_x000D_
  align-items: stretch;_x000D_
  height: 300px;_x000D_
  grid-template-rows: min-content auto 60px;_x000D_
}_x000D_
header {_x000D_
  background: tomato;_x000D_
}_x000D_
div {_x000D_
  background: gold;_x000D_
  overflow: auto;_x000D_
}_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    _x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    _x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

How can I search Git branches for a file or directory?

git ls-tree might help. To search across all existing branches:

for branch in `git for-each-ref --format="%(refname)" refs/heads`; do
  echo $branch :; git ls-tree -r --name-only $branch | grep '<foo>'
done

The advantage of this is that you can also search with regular expressions for the file name.

Extract a subset of a dataframe based on a condition involving a field

Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:

    bar <- foo[foo[ ,1] == "there", ]

This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).

This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:

    foo[foo[ ,c(1:N)], ]

Or specific columns, as you would expect.

    foo[foo[ ,c(1,5,9)], ]

Logical operators ("and", "or") in DOS batch

OR is slightly tricky, but not overly so. Here is an example

set var1=%~1
set var2=%~2
::
set or_=
if "%var1%"=="Stack" set or_=true
if "%var2%"=="Overflow" set or_=true
if defined or_ echo Stack OR Overflow

Should we @Override an interface's method implementation?

You should use @Override whenever possible. It prevents simple mistakes from being made. Example:

class C {
    @Override
    public boolean equals(SomeClass obj){
        // code ...
    }
}

This doesn't compile because it doesn't properly override public boolean equals(Object obj).

The same will go for methods that implement an interface (1.6 and above only) or override a Super class's method.

Laravel Blade html image

In Laravel 5.x you can use laravelcollective/html and the syntax:

{!! Html::image('img/logo.png') !!}

Is it possible to ping a server from Javascript?

I don't know what version of Ruby you're running, but have you tried implementing ping for ruby instead of javascript? http://raa.ruby-lang.org/project/net-ping/

Is it possible to log all HTTP request headers with Apache?

In my case easiest way to get browser headers was to use php. It appends headers to file and prints them to test page.

<?php
$fp = fopen('m:/temp/requests.txt', 'a');
$time = $_SERVER['REQUEST_TIME'];
fwrite($fp, $time  "\n");
echo "$time.<br>";
foreach (getallheaders() as $name => $value) {
    $cur_hd = "$name: $value\n";
    fwrite($fp, $cur_hd);
    echo "$cur_hd.<br>";
}
fwrite($fp, "***\n");
fclose($fp);
?>

How can I set the current working directory to the directory of the script in Bash?

I take this and it works.

#!/bin/bash
cd "$(dirname "$0")"
CUR_DIR=$(pwd)

What is the volatile keyword useful for?

Every thread accessing a volatile field will read its current value before continuing, instead of (potentially) using a cached value.

Only member variable can be volatile or transient.

Loop through JSON object List

I have the following call:

$('#select_box_id').change(function() {
        var action = $('#my_form').attr('action');
    $.get(action,{},function(response){
        $.each(response.result,function(i) {

            alert("key is: " + i + ", val is: " + response.result[i]);

        });
    }, 'json');
    });

The structure coming back from the server look like:

{"result":{"1":"waterskiing","2":"canoeing","18":"windsurfing"}}

CSS3 Rotate Animation

To achieve the 360 degree rotation, here is the Working Solution.

The HTML:

<img class="image" src="your-image.png">

The CSS:

.image {
    overflow: hidden;
    transition-duration: 0.8s;
    transition-property: transform;
}
.image:hover {
    transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
}

You have to hover on the image and you will get the 360 degree rotation effect.

PS: Add a -webkit- extension for it to work on chrome and other webkit browers. You can check the updated fiddle for webkit HERE

Converting Symbols, Accent Letters to English Alphabet

If the need is to convert "òéisöç->oeisoc", you can use this a starting point :

public class AsciiUtils {
    private static final String PLAIN_ASCII =
      "AaEeIiOoUu"    // grave
    + "AaEeIiOoUuYy"  // acute
    + "AaEeIiOoUuYy"  // circumflex
    + "AaOoNn"        // tilde
    + "AaEeIiOoUuYy"  // umlaut
    + "Aa"            // ring
    + "Cc"            // cedilla
    + "OoUu"          // double acute
    ;

    private static final String UNICODE =
     "\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"             
    + "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD" 
    + "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177" 
    + "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
    + "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF" 
    + "\u00C5\u00E5"                                                             
    + "\u00C7\u00E7" 
    + "\u0150\u0151\u0170\u0171" 
    ;

    // private constructor, can't be instanciated!
    private AsciiUtils() { }

    // remove accentued from a string and replace with ascii equivalent
    public static String convertNonAscii(String s) {
       if (s == null) return null;
       StringBuilder sb = new StringBuilder();
       int n = s.length();
       for (int i = 0; i < n; i++) {
          char c = s.charAt(i);
          int pos = UNICODE.indexOf(c);
          if (pos > -1){
              sb.append(PLAIN_ASCII.charAt(pos));
          }
          else {
              sb.append(c);
          }
       }
       return sb.toString();
    }

    public static void main(String args[]) {
       String s = 
         "The result : È,É,Ê,Ë,Û,Ù,Ï,Î,À,Â,Ô,è,é,ê,ë,û,ù,ï,î,à,â,ô,ç";
       System.out.println(AsciiUtils.convertNonAscii(s));
       // output : 
       // The result : E,E,E,E,U,U,I,I,A,A,O,e,e,e,e,u,u,i,i,a,a,o,c
    }
}

The JDK 1.6 provides the java.text.Normalizer class that can be used for this task.

See an example here

String concatenation of two pandas columns

The problem in your code is that you want to apply the operation on every row. The way you've written it though takes the whole 'bar' and 'foo' columns, converts them to strings and gives you back one big string. You can write it like:

df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)

It's longer than the other answer but is more generic (can be used with values that are not strings).

CSS: center element within a <div> element

If you want to center elements inside a div and don't care about division size you could use Flex power. I prefer using flex and don't use exact size for elements.

<div class="outer flex">
    <div class="inner">
        This is the inner Content
    </div>
</div>

As you can see Outer div is Flex container and Inner must be Flex item that specified with flex: 1 1 auto; for better understand you could see this simple sample. http://jsfiddle.net/QMaster/hC223/

Hope this help.

Count distinct value pairs in multiple columns in SQL

Having to return the count of a unique Bill of Materials (BOM) where each BOM have multiple positions, I dd something like this:

select t_item, t_pono, count(distinct ltrim(rtrim(t_item)) + cast(t_pono as varchar(3))) as [BOM Pono Count]
from BOMMaster
where t_pono = 1
group by t_item, t_pono

Given t_pono is a smallint datatype and t_item is a varchar(16) datatype

Fatal error: Call to a member function query() on null

put this line in parent construct : $this->load->database();

function  __construct() {
    parent::__construct();
    $this->load->library('lib_name');
    $model=array('model_name');
    $this->load->model($model);
    $this->load->database();
}

this way.. it should work..

Understanding ASP.NET Eval() and Bind()

For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use Bind.

Imagine for example a GridView with a ItemTemplate and EditItemTemplate. If you use Bind or Eval in the ItemTemplate, there will be no difference. If you use Eval in the EditItemTemplate, the value will not be able to be passed to the Update method of the DataSource that the grid is bound to.


UPDATE: I've come up with this example:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Data binding demo</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView 
            ID="grdTest" 
            runat="server" 
            AutoGenerateEditButton="true" 
            AutoGenerateColumns="false" 
            DataSourceID="mySource">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("Name") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox 
                            ID="edtName" 
                            runat="server" 
                            Text='<%# Bind("Name") %>' 
                        />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>

    <asp:ObjectDataSource 
        ID="mySource" 
        runat="server"
        SelectMethod="Select" 
        UpdateMethod="Update" 
        TypeName="MyCompany.CustomDataSource" />
</body>
</html>

And here's the definition of a custom class that serves as object data source:

public class CustomDataSource
{
    public class Model
    {
        public string Name { get; set; }
    }

    public IEnumerable<Model> Select()
    {
        return new[] 
        {
            new Model { Name = "some value" }
        };
    }

    public void Update(string Name)
    {
        // This method will be called if you used Bind for the TextBox
        // and you will be able to get the new name and update the
        // data source accordingly
    }

    public void Update()
    {
        // This method will be called if you used Eval for the TextBox
        // and you will not be able to get the new name that the user
        // entered
    }
}

Generate random numbers uniformly over an entire range

Check what RAND_MAX is on your system -- I'm guessing it is only 16 bits, and your range is too big for it.

Beyond that see this discussion on: Generating Random Integers within a Desired Range and the notes on using (or not) the C rand() function.

nil detection in Go

The compiler is pointing the error to you, you're comparing a structure instance and nil. They're not of the same type so it considers it as an invalid comparison and yells at you.

What you want to do here is to compare a pointer to your config instance to nil, which is a valid comparison. To do that you can either use the golang new builtin, or initialize a pointer to it:

config := new(Config) // not nil

or

config := &Config{
                  host: "myhost.com", 
                  port: 22,
                 } // not nil

or

var config *Config // nil

Then you'll be able to check if

if config == nil {
    // then
}

Best way to add Gradle support to IntelliJ Project

In IntelliJ 2017.2.4 I just closed the project and reopened it and I got a dialog asking me if I wanted to link with build.gradle which opened up the import dialog for Gradle projects.

No need to delete any files or add the idea plugin to build.gradle.

Perl - Multiple condition if statement without duplicating code?

Simple:

if ( $name eq 'tom' && $password eq '123!'
    || $name eq 'frank' && $password eq '321!'
) {

(use the high-precedence && and || in expressions, reserving and and or for flow control, to avoid common precedence errors)

Better:

my %password = (
    'tom' => '123!',
    'frank' => '321!',
);

if ( exists $password{$name} && $password eq $password{$name} ) {

Accessing a property in a parent Component

On Angular 6, I access parent properties by injecting the parent via constructor. Not the best solution but it works:

 constructor(@Optional() public parentComponentInjectionObject: ParentComponent){
    // And access like this:
    parentComponentInjectionObject.thePropertyYouWantToAccess;
}

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

Look for GSpread.NET. It's also an OpenSource project and it doesn't require Office installed. You can work with Google Spreadsheets by using API from Microsoft Excel. If you want to re-use the old code to get access to Google Spreadsheets, GSpread.NET is the best way. You need to add a few row:

Set objExcel = CreateObject("GSpreadCOM.Application")
// Name             - User name, any you like
// ClientIdAndSecret - `client_id|client_secret` format
// ScriptId         - Google Apps script ID
app.MailLogon(Name, ClientIdAndSecret, ScriptId);

Further code remain unchanged.

http://scand.com/products/gspread/index.html

How to use multiprocessing pool.map with multiple arguments?

A better solution for python2:

from multiprocessing import Pool
def func((i, (a, b))):
    print i, a, b
    return a + b
pool = Pool(3)
pool.map(func, [(0,(1,2)), (1,(2,3)), (2,(3, 4))])

2 3 4

1 2 3

0 1 2

out[]:

[3, 5, 7]

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

How to copy files from host to Docker container?

I usually create python server using this command

python -m SimpleHTTPServer

in the particular directory and then just use wget to transfer file in the desired location in docker. I know it is not the best way to do it but I find it much easier.

Replace string within file contents

easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where 'A' would be stored) you do...

import re

input = file('C:\full_path\Stud.txt), 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file.  So we have to save the file first.

saved_input
for eachLine in input:
    saved_input.append(eachLine)

#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
    search = re.sub('A', 'Orange', saved_input[i])
    if search is not None:
        saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt), 'w')
for each in saved_input:
    input.write(each)

python paramiko ssh

###### Use paramiko to connect to LINUX platform############
import paramiko

ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

--------Connection Established-----------------------------

######To run shell commands on remote connection###########
import paramiko

ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)


stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp) # Output 

Get all unique values in a JavaScript array (remove duplicates)

Reduce it!!!

This alternative instead of deduplicating explicitly it will take the array and reduce it so that each value of the array can be iterated and destructured in an accumulative behavior, ignoring the already included values by exploiting the persistence of the array because of the recursiveness.

['a', 1, 'a', 2, '1'].reduce((accumulator, currentValue) => accumulator.includes(currentValue) ? accumulator : [...accumulator, currentValue], [])

Test Example:

_x000D_
_x000D_
var array = ['a', 1, 'a', 2, '1'];_x000D_
const reducer = (accumulator, currentValue) => accumulator.includes(currentValue) ? accumulator : [...accumulator, currentValue];_x000D_
_x000D_
console.log(_x000D_
  array.reduce(reducer, [])_x000D_
);
_x000D_
_x000D_
_x000D_

Conclusion

By far more elegant and useful when boring for-each approach wants to be avoided (not that it is not useful).

No need for external libraries like Underscore.js, JQuery or Lo-Dash, nor the trouble to create any built-in function to achieve the desired deduplicated effect.

Oh, and HEY!, it can be done as a one-liner!!!


This answered was possible thanks to ES5 (ECMAScript 2015) include() and reduce().

How to delete images from a private docker registry?

Another tool you can use is registry-cli. For example, this command:

registry.py -l "login:password" -r https://your-registry.example.com --delete

will delete all but the last 10 images.

Add and remove attribute with jquery

First you to add a class then remove id

<script type="text/javascript">
$(document).ready(function(){   
 $("#page_navigation1").addClass("page_navigation");        

 $("#add").click(function(){
        $(".page_navigation").attr("id","page_navigation1");
    });     
    $("#remove").click(function(){
        $(".page_navigation").removeAttr("id");
    });     
  });
</script>

Python variables as keys to dict

Well this is a bit, umm ... non-Pythonic ... ugly ... hackish ...

Here's a snippet of code assuming you want to create a dictionary of all the local variables you create after a specific checkpoint is taken:

checkpoint = [ 'checkpoint' ] + locals().keys()[:]
## Various local assigments here ...
var_keys_since_checkpoint = set(locals().keys()) - set(checkpoint)
new_vars = dict()
for each in var_keys_since_checkpoint:
   new_vars[each] = locals()[each]

Note that we explicitly add the 'checkpoint' key into our capture of the locals().keys() I'm also explicitly taking a slice of that though it shouldn't be necessary in this case since the reference has to be flattened to add it to the [ 'checkpoint' ] list. However, if you were using a variant of this code and tried to shortcut out the ['checkpoint'] + portion (because that key was already inlocals(), for example) ... then, without the [:] slice you could end up with a reference to thelocals().keys()` whose values would change as you added variables.

Offhand I can't think of a way to call something like new_vars.update() with a list of keys to be added/updated. So thefor loop is most portable. I suppose a dictionary comprehension could be used in more recent versions of Python. However that woudl seem to be nothing more than a round of code golf.