Programs & Examples On #Subviews

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

tsc throws `TS2307: Cannot find module` for a local file

I was in trouble to import an Enum in typescript

error TS2307: Cannot find module...

What I did to make it work was migrate the enum to another file and make this change:

export enum MyEnum{
    VALUE = "MY_VALUE"
}

to

export enum MyEnum{
    VALUE = 1
}

UICollectionView - dynamic cell height?

I followed the steps mentioned in this SO and everything is fine except when my Collection View has less data (text) to make it wide enough. Checking the documentation in systemLyaoutSizeFittingSize, I have this solution so my cell take up the width as I requested:

- (CGSize)calculateSizeForSizingCell:(UICollectionViewCell *)sizingCell width:(CGFloat)width {
    CGRect frame = sizingCell.frame;
    frame.size.width = width;
    sizingCell.frame = frame;
    [sizingCell setNeedsLayout];
    [sizingCell layoutIfNeeded];

    CGSize size = [sizingCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize
                        withHorizontalFittingPriority:UILayoutPriorityRequired
                              verticalFittingPriority:UILayoutPriorityFittingSizeLevel];
    return size;
}

Hope this would help someone.

- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize NS_AVAILABLE_IOS(6_0);

Apple doc:

Equivalent to sending -systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority: with UILayoutPriorityFittingSizeLevel for both priorities.

While the default value is "pretty low" according to Apple's doc:

When you send -[UIView systemLayoutSizeFittingSize:], the size fitting most closely to the target size (the argument) is computed. UILayoutPriorityFittingSizeLevel is the priority level with which the view wants to conform to the target size in that computation. It's quite low. It is generally not appropriate to make a constraint at exactly this priority. You want to be higher or lower.

So my change of default behavior is to enforce the width (horizontal fitting) with UILayoutPriorityRequired.

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

Go into Simulator-> Hardware->Keyboard and unchecking Connect Hardware Keyboard.

The same as many answers above BUT did not change for me until I quit and restart the simulator. xcode 8.2.1 and Simulator 10.0.

How to remove all subviews of a view in Swift?

For Swift 3

I did as following because just removing from superview did not erase the buttons from array.

    for k in 0..<buttons.count {

      buttons[k].removeFromSuperview()

    }


    buttons.removeAll()

How to use UIVisualEffectView to Blur Image?

You can also use the interface builder to create these effects easily for simple situations. Since the z-values of the views will depend on the order they are listed in the Document Outline, you can drag a UIVisualEffectView onto the document outline before the view you want to blur. This automatically creates a nested UIView, which is the contentView property of the given UIVisualEffectView. Nest things within this view that you want to appear on top of the blur.

XCode6 beta5

You can also easily take advantage of the vibrancy UIVisualEffect, which will automatically create another nested UIVisualEffectView in the document outline with vibrancy enabled by default. You can then add a label or text view to the nested UIView (again, the contentView property of the UIVisualEffectView), to achieve the same effect that the "> slide to unlock" UI element.

enter image description here

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

swift 4

    @IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var tableView: UITableView!
    private var context = 1
 override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.addObserver(self, forKeyPath: "contentSize", options: [.new,.prior], context: &context)
    }
  // Added observer to adjust tableview height based on the content

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if context == &self.context{
            if let size = change?[NSKeyValueChangeKey.newKey] as? CGSize{
                print("-----")
                print(size.height)
                tableViewHeightConstraint.constant = size.height + 50
            }
        }
    }

//Remove observer
 deinit {

        NotificationCenter.default.removeObserver(self)

    }

How to resize superview to fit all subviews with autolayout?

Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.

Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.

//
//  ViewController.m
//  AutoLayoutDynamicVerticalContainerHeight
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end

@implementation ViewController

- (void)viewDidLoad
{
    // INVOKE SUPER
    [super viewDidLoad];

    // INIT ALL REQUIRED UI ELEMENTS
    self.contentView = [[UIView alloc] init];
    self.myLabel = [[UILabel alloc] init];
    self.myOtherLabel = [[UILabel alloc] init];
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);

    // TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // ESTABLISH VIEW HIERARCHY
    [self.view addSubview:self.contentView]; // View adds content view
    [self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
    [self.contentView addSubview:self.myOtherLabel];

    // LAYOUT

    // Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
    // Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet

    /* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
    // ^To me this is what's weird... but okay once you understand...

    // Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];

    // Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
    // Note, this is the view that we are choosing to use to drive the height (and width) of our container...

    // The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // COLOR VIEWS
    self.view.backgroundColor = [UIColor purpleColor];
    self.contentView.backgroundColor = [UIColor redColor];
    self.myLabel.backgroundColor = [UIColor orangeColor];
    self.myOtherLabel.backgroundColor = [UIColor greenColor];

    // CONFIGURE VIEWS

    // Configure MY LABEL
    self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
    self.myLabel.numberOfLines = 0; // Let it flow

    // Configure MY OTHER LABEL
    self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
    self.myOtherLabel.numberOfLines = 0;
    self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}

@end

How to resize superview to fit all subviews with autolayout.png

How to use auto-layout to move other views when a view is hidden?

Adding or removing constraints during runtime is a heavyweight operation that can affect performance. However, there is a simpler alternative.

For the view you wish to hide, set up a width constraint. Constrain the other views with a leading horizontal gap to that view.

To hide, update the .constant of the width constraint to 0.f. The other views will automatically move left to assume position.

See my other answer here for more details:

How to change label constraints during runtime?

Status bar and navigation bar appear over my view's bounds in iOS 7

To me, the simplest solution is to add two keys into the plist

enter image description here

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

This happened to me in the following scenario:

I created a second project in my workspace, chose "Single View Application" for the template.

I then went to Interface Builder (main iPhone storyboard), added a UISwitch to the main view, and connected it to the view controller through both an IBOutlet and an IBAction (-valueChanged:).

On launch, the app crashes with the exception mentioned in the question. If I remove the switch from the view, it works.

After careful inspection, I realized I control-dragged the connections into the ViewController.h of another project in the same workspace. The 'Automatic' set of Interface Builder's Assistant Editor (a.k.a Tuxedo chest icon) chose as "counterpart" the wrong file (with the right name).

Hope this helps someone, specially because both 'Single View Application' and 'SpriteKit Game' project templates (in my case) create a default view controller class called "ViewController".

iOS: Multi-line UILabel in Auto Layout

Use -setPreferredMaxLayoutWidth on the UILabel and autolayout should handle the rest.

[label setPreferredMaxLayoutWidth:200.0];

See the UILabel documentation on preferredMaxLayoutWidth.

Update:

Only need to set the height constraint in storyboard to Greater than or equal to, no need to setPreferredMaxLayoutWidth.

Should IBOutlets be strong or weak under ARC?

One thing I wish to point out here, and that is, despite what the Apple engineers have stated in their own WWDC 2015 video here:

https://developer.apple.com/videos/play/wwdc2015/407/

Apple keeps changing their mind on the subject, which tells us that there is no single right answer to this question. To show that even Apple engineers are split on this subject, take a look at Apple's most recent sample code, and you'll see some people use weak, and some don't.

This Apple Pay example uses weak: https://developer.apple.com/library/ios/samplecode/Emporium/Listings/Emporium_ProductTableViewController_swift.html#//apple_ref/doc/uid/TP40016175-Emporium_ProductTableViewController_swift-DontLinkElementID_8

As does this picture-in-picture example: https://developer.apple.com/library/ios/samplecode/AVFoundationPiPPlayer/Listings/AVFoundationPiPPlayer_PlayerViewController_swift.html#//apple_ref/doc/uid/TP40016166-AVFoundationPiPPlayer_PlayerViewController_swift-DontLinkElementID_4

As does the Lister example: https://developer.apple.com/library/ios/samplecode/Lister/Listings/Lister_ListCell_swift.html#//apple_ref/doc/uid/TP40014701-Lister_ListCell_swift-DontLinkElementID_57

As does the Core Location example: https://developer.apple.com/library/ios/samplecode/PotLoc/Listings/Potloc_PotlocViewController_swift.html#//apple_ref/doc/uid/TP40016176-Potloc_PotlocViewController_swift-DontLinkElementID_6

As does the view controller previewing example: https://developer.apple.com/library/ios/samplecode/ViewControllerPreviews/Listings/Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift.html#//apple_ref/doc/uid/TP40016546-Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift-DontLinkElementID_5

As does the HomeKit example: https://developer.apple.com/library/ios/samplecode/HomeKitCatalog/Listings/HMCatalog_Homes_Action_Sets_ActionSetViewController_swift.html#//apple_ref/doc/uid/TP40015048-HMCatalog_Homes_Action_Sets_ActionSetViewController_swift-DontLinkElementID_23

All those are fully updated for iOS 9, and all use weak outlets. From this we learn that A. The issue is not as simple as some people make it out to be. B. Apple has changed their mind repeatedly, and C. You can use whatever makes you happy :)

Special thanks to Paul Hudson (author of www.hackingwithsift.com) who gave me the clarification, and references for this answer.

I hope this clarifies the subject a bit better!

Take care.

Programmatically get height of navigation bar

With iPhone-X, height of top bar (navigation bar + status bar) is changed (increased).

Try this if you want exact height of top bar (both navigation bar + status bar):

UPDATE

iOS 13

As the statusBarFrame was deprecated in iOS13 you can use this:

extension UIViewController {

    /**
     *  Height of status bar + navigation bar (if navigation bar exist)
     */

    var topbarHeight: CGFloat {
        return (view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) +
            (self.navigationController?.navigationBar.frame.height ?? 0.0)
    }
}

Objective-C

CGFloat topbarHeight = ([UIApplication sharedApplication].statusBarFrame.size.height +
       (self.navigationController.navigationBar.frame.size.height ?: 0.0));

Swift 4

let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
        (self.navigationController?.navigationBar.frame.height ?? 0.0)

For ease, try this UIViewController extension

extension UIViewController {

    /**
     *  Height of status bar + navigation bar (if navigation bar exist)
     */

    var topbarHeight: CGFloat {
        return UIApplication.shared.statusBarFrame.size.height +
            (self.navigationController?.navigationBar.frame.height ?? 0.0)
    }
}

Swift 3

let topBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)

Getting reference to the top-most view/window in iOS application

Just use this code if you want to add a view above of everything in the screen.

[[UIApplication sharedApplication].keyWindow addSubView: yourView];

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

This worked for me in swift:

Create a subclass of UITableViewCell (make sure you link up your cell in the storyboard)

class MyTableCell:UITableViewCell{
    override func layoutSubviews() {
        super.layoutSubviews()

        if(self.imageView?.image != nil){

            let cellFrame = self.frame
            let textLabelFrame = self.textLabel?.frame
            let detailTextLabelFrame = self.detailTextLabel?.frame
            let imageViewFrame = self.imageView?.frame

            self.imageView?.contentMode = .ScaleAspectFill
            self.imageView?.clipsToBounds = true
            self.imageView?.frame = CGRectMake((imageViewFrame?.origin.x)!,(imageViewFrame?.origin.y)! + 1,40,40)
            self.textLabel!.frame = CGRectMake(50 + (imageViewFrame?.origin.x)! , (textLabelFrame?.origin.y)!, cellFrame.width-(70 + (imageViewFrame?.origin.x)!), textLabelFrame!.height)
            self.detailTextLabel!.frame = CGRectMake(50 + (imageViewFrame?.origin.x)!, (detailTextLabelFrame?.origin.y)!, cellFrame.width-(70 + (imageViewFrame?.origin.x)!), detailTextLabelFrame!.height)
        }
    }
}

In cellForRowAtIndexPath , dequeue the cell as your new cell type:

    let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as! MyTableCell

Obviously change number values to suit your layout

Remove all subviews?

Get all the subviews from your root controller and send each a removeFromSuperview:

NSArray *viewsToRemove = [self.view subviews];
for (UIView *v in viewsToRemove) {
    [v removeFromSuperview];
}

Detecting which UIButton was pressed in a UITableView

This problem has two parts:

1) Getting the index path of UITableViewCell which contains pressed UIButton

There are some suggestions like:

  • Updating UIButton's tag in cellForRowAtIndexPath: method using index path's row value. This is not an good solution as it requires updating tag continuously and it does not work with table views with more than one section.

  • Adding an NSIndexPath property to custom cell and updating it instead of UIButton's tag in cellForRowAtIndexPath: method. This solves multiple section problem but still not good as it requires updating always.

  • Keeping a weak refence to parent UITableView in the custom cell while creating it and using indexPathForCell: method to get the index path. Seems a little bit better, no need to update anything in cellForRowAtIndexPath: method, but still requires setting a weak reference when the custom cell is created.

  • Using cell's superView property to get a reference to parent UITableView. No need to add any properties to the custom cell, and no need to set/update anything on creation/later. But cell's superView depends on iOS implementation details. So it can not be used directly.

But this can be achieved using a simple loop, as we are sure the cell in question has to be in a UITableView:

UIView* view = self;
while (view && ![view isKindOfClass:UITableView.class])
    view = view.superview;
UITableView* parentTableView = (UITableView*)view;

So, these suggestions can be combined into a simple and safe custom cell method for getting the index path:

- (NSIndexPath *)indexPath
{
    UIView* view = self;

    while (view && ![view isKindOfClass:UITableView.class])
        view = view.superview;

    return [(UITableView*)view indexPathForCell:self];
}

From now on, this method can be used to detect which UIButton is pressed.

2) Informing other parties about button press event

After internally knowing which UIButton is pressed in which custom cell with exact index path, this information needs to be sent to other parties (most probably the view controller handling the UITableView). So, this button click event can be handled in a similar abstraction and logic level to didSelectRowAtIndexPath: method of UITableView delegate.

Two approaches can be used for this:

a) Delegation: custom cell can have a delegate property and can define a protocol. When button is pressed it just performs it's delegate methods on it's delegate property. But this delegate property needs to be set for each custom cell when they are created. As an alternative, custom cell can choose to perform its delegate methods on it's parent table view's delegate too.

b) Notification Center: custom cells can define a custom notification name and post this notification with the index path and parent table view information provided in userInfo object. No need to set anything for each cell, just adding an observer for the custom cell's notification is enough.

Making view resize to its parent when added with addSubview

If you aren’t using Auto Layout, have you tried setting the child view’s autoresize mask? Try this:

myChildeView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                                 UIViewAutoresizingFlexibleHeight);

Also, you may need to call

myParentView.autoresizesSubviews = YES;

to get the parent view to resize its subviews automatically when its frame changes.

If you’re still seeing the child view drawing outside of the parent view’s frame, there’s a good chance that the parent view is not clipping its contents. To fix that, call

myParentView.clipsToBounds = YES;

What is the most robust way to force a UIView to redraw?

I had the same problem, and all the solutions from SO or Google didn't work for me. Usually, setNeedsDisplay does work, but when it doesn't...
I've tried calling setNeedsDisplay of the view just every possible way from every possible threads and stuff - still no success. We know, as Rob said, that

"this needs to be drawn in the next draw cycle."

But for some reason it wouldn't draw this time. And the only solution I've found is calling it manually after some time, to let anything that blocks the draw pass away, like this:

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 
                                        (int64_t)(0.005 * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
    [viewToRefresh setNeedsDisplay];
});

It's a good solution if you don't need the view to redraw really often. Otherwise, if you're doing some moving (action) stuff, there is usually no problems with just calling setNeedsDisplay.

I hope it will help someone who is lost there, like I was.

How to add an UIViewController's view as subview

Change the frame size of viewcontroller.view.frame, and then add to subview. [viewcontrollerparent.view addSubview:viewcontroller.view]

When is layoutSubviews called?

A rather obscure, yet potentially important case when layoutSubviews never gets called is:

import UIKit

class View: UIView {

    override class var layerClass: AnyClass { return Layer.self }

    class Layer: CALayer {
        override func layoutSublayers() {
            // if we don't call super.layoutSublayers()...
            print(type(of: self), #function)
        }
    }

    override func layoutSubviews() {
        // ... this method never gets called by the OS!
        print(type(of: self), #function)
    }
}

let view = View(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

How do you add multi-line text to a UIButton?

You have to add this code:

buttonLabel.titleLabel.numberOfLines = 0;

Setting custom UITableViewCells height

#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 300.0f
#define CELL_CONTENT_MARGIN 10.0f

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath      *)indexPath;
{
   /// Here you can set also height according to your section and row
   if(indexPath.section==0 && indexPath.row==0)
   {
     text=@"pass here your dynamic data";

     CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

     CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]      constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

     CGFloat height = MAX(size.height, 44.0f);

     return height + (CELL_CONTENT_MARGIN * 2);
   }
   else
   {
      return 44;
   }
}

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    UILabel *label = nil;

    cell = [tv dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil)
    {
       cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"];
    }
    ********Here you can set also height according to your section and row*********
    if(indexPath.section==0 && indexPath.row==0)
    {
        label = [[UILabel alloc] initWithFrame:CGRectZero];
        [label setLineBreakMode:UILineBreakModeWordWrap];
        [label setMinimumFontSize:FONT_SIZE];
        [label setNumberOfLines:0];
        label.backgroundColor=[UIColor clearColor];
        [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
        [label setTag:1];

        // NSString *text1 =[NSString stringWithFormat:@"%@",text];

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        if (!label)
        label = (UILabel*)[cell viewWithTag:1];


        label.text=[NSString stringWithFormat:@"%@",text];
        [label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH          - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
        [cell.contentView addSubview:label];
    }
return cell;
}

I need to learn Web Services in Java. What are the different types in it?

  1. SOAP Web Services are standard-based and supported by almost every software platform: They rely heavily in XML and have support for transactions, security, asynchronous messages and many other issues. It’s a pretty big and complicated standard, but covers almost every messaging situation. On the other side, RESTful services relies of HTTP protocol and verbs (GET, POST, PUT, DELETE) to interchange messages in any format, preferable JSON and XML. It’s a pretty simple and elegant architectural approach.
  2. As in every topic in the Java World, there are several libraries to build/consume Web Services. In the SOAP Side you have the JAX-WS standard and Apache Axis, and in REST you can use Restlets or Spring REST Facilities among other libraries.

With question 3, this article states that RESTful Services are appropiate in this scenarios:

  • If you have limited bandwidth
  • If your operations are stateless: No information is preserved from one invocation to the next one, and each request is treated independently.
  • If your clients require caching.

While SOAP is the way to go when:

  • If you require asynchronous processing
  • If you need formal contract/Interfaces
  • In your service operations are stateful: For example, you store information/data on a request and use that stored data on the next one.

change directory in batch file using variable

The set statement doesn't treat spaces the way you expect; your variable is really named Pathname[space] and is equal to [space]C:\Program Files.

Remove the spaces from both sides of the = sign, and put the value in double quotes:

set Pathname="C:\Program Files"

Also, if your command prompt is not open to C:\, then using cd alone can't change drives.

Use

cd /d %Pathname%

or

pushd %Pathname%

instead.

How to define servlet filter order of execution using annotations in WAR

  1. Make the servlet filter implement the spring Ordered interface.
  2. Declare the servlet filter bean manually in configuration class.
    import org.springframework.core.Ordered;
    
    public class MyFilter implements Filter, Ordered {

        @Override
        public void init(FilterConfig filterConfig) {
            // do something
        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            // do something
        }

        @Override
        public void destroy() {
            // do something
        }

        @Override
        public int getOrder() {
            return -100;
        }
    }


    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;

    @Configuration
    @ComponentScan
    public class MyAutoConfiguration {

        @Bean
        public MyFilter myFilter() {
            return new MyFilter();
        }
    }

How to append a char to a std::string?

If you are using the push_back there is no call for the string constructor. Otherwise it will create a string object via casting, then it will add the character in this string to the other string. Too much trouble for a tiny character ;)

Push JSON Objects to array in localStorage

There are a few steps you need to take to properly store this information in your localStorage. Before we get down to the code however, please note that localStorage (at the current time) cannot hold any data type except for strings. You will need to serialize the array for storage and then parse it back out to make modifications to it.

Step 1:

The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:

var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));

The above code should only be run once and only if you are not already storing an array in your localStorage session variable. If you are already doing this skip to step 2.

Step 2:

Modify your function like so:

function SaveDataToLocalStorage(data)
{
    var a = [];
    // Parse the serialized data back into an aray of objects
    a = JSON.parse(localStorage.getItem('session')) || [];
    // Push the new data (whether it be an object or anything else) onto the array
    a.push(data);
    // Alert the array value
    alert(a);  // Should be something like [Object array]
    // Re-serialize the array back into a string and store it in localStorage
    localStorage.setItem('session', JSON.stringify(a));
}

This should take care of the rest for you. When you parse it out, it will become an array of objects.

Hope this helps.

If Radio Button is selected, perform validation on Checkboxes

You need to use == or === for comparison. = assigns a new value.

Besides that, using == is pointless when dealing with booleans only. Just use if(foo) instead of if(foo == true).

jQuery.click() vs onClick

Performance

There are already many good answers here however, authors sometimes mention about performance but actually nobody investigate it yet - so I will focus on this aspect here. Today I perform test on Chrome 83.0, Safari 13.1 and Firefox 77.0 for solutions mention in question and additionally few alternative solutions (some of them was mention in other answers).

Results

I compare here solutions A-H because they operate on elements id. I also show results for solutions which use class (I,J,K) as reference.

  • solution based on html-inline handler binding (B) is fast and fastest for Chrome and fastest for small number of elements
  • solutions based on getElementById (C,D) are fast, and for big number of elements fastest on Safari and Firefox
  • referenced solutions I,J based are fastest for big num of elements so It is worth to consider use class instead id approach in this case
  • solution based on jQuery.click (A) is slowest

enter image description here

Details

Actually It was not easy to design performance test for this question. I notice that for all tested solutions, performance of triggering events for 10K div-s was fast and manually I was not able to detect any differences between them (you can run below snippet to check it yourself). So I focus on measure execution time of generate html and bind event handlers for two cases

  • 10 divs - you can run test HERE
  • 1000 divs - you can run test HERE

_x000D_
_x000D_
// https://stackoverflow.com/questions/12627443/jquery-click-vs-onclick
let a= [...Array(10000)];

function clean() { test.innerHTML = ''; console.clear() }

function divFunction(el) {
  console.log(`clicked on: ${el.id}`);
}

function initA() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> $(`#myDiv${i}`).click(e=> divFunction(e.target)));
}

function initB() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box" onclick="divFunction(this)">${i}</div>`).join``;
}

function initC() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> document.getElementById(`myDiv${i}`).onclick = e=> divFunction(e.target) );
}

function initD() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> document.getElementById(`myDiv${i}`).addEventListener('click', e=> divFunction(e.target) ));
}

function initE() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> document.querySelector(`#myDiv${i}`).onclick = e=> divFunction(e.target) );
}

function initF() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> document.querySelector(`#myDiv${i}`).addEventListener('click', e=> divFunction(e.target) ));
}

function initG() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> window[`myDiv${i}`].onclick = e=> divFunction(e.target) );
}

function initH() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> window[`myDiv${i}`].addEventListener('click',e=> divFunction(e.target)));
}

function initI() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  [...document.querySelectorAll(`.box`)].map(el => el.onclick = e=> divFunction(e.target));
}

function initJ() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  [...document.querySelectorAll(`.box`)].map(el => el.addEventListener('click', e=> divFunction(e.target)));
}

function initK() {  
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  $(`.box`).click(e=> divFunction(e.target));
}



function measure(f) {  
  console.time("measure "+f.name);
  f();
  console.timeEnd("measure "+f.name)
}
_x000D_
#test {
  display: flex;
  flex-wrap: wrap;
}

.box {
  margin: 1px;
  height: 10px;
  background: red;
  font-size: 10px;
  cursor: pointer;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>This snippet only presents used solutions. Click to solution button and then click on any red box to trigger its handler</div>
<button onclick="measure(initA)">A</button>
<button onclick="measure(initB)">B</button>
<button onclick="measure(initC)">C</button>
<button onclick="measure(initD)">D</button>
<button onclick="measure(initE)">E</button>
<button onclick="measure(initF)">F</button>
<button onclick="measure(initG)">G</button>
<button onclick="measure(initH)">H</button>
<button onclick="measure(initI)">I</button>
<button onclick="measure(initJ)">J</button>
<button onclick="measure(initK)">K</button>
<button onclick="clean()">Clean</button>

<div id="test"></div>
_x000D_
_x000D_
_x000D_

Here is example test for Chrome

enter image description here

Intersection and union of ArrayLists in Java

list1.retainAll(list2) - is intersection

union will be removeAll and then addAll.

Find more in the documentation of collection(ArrayList is a collection) http://download.oracle.com/javase/1.5.0/docs/api/java/util/Collection.html

Could not find server 'server name' in sys.servers. SQL Server 2014

I had the problem due to an extra space in the name of the linked server. "SERVER1, 1234" instead of "SERVER1,1234"

How to clear cache of Eclipse Indigo

you can use -clean parameter while starting eclipse like

C:\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.6.0_24\bin" -clean

PHP Echo text Color

Try this

<?php 
echo '<i style="color:blue;font-size:30px;font-family:calibri ;">
      hello php color </i> ';
//we cannot use double quote after echo , it must be single quote.
?>

Top 5 time-consuming SQL queries in Oracle

While searching I got the following query which does the job with one assumption(query execution time >6 seconds)


SELECT username, sql_text, sofar, totalwork, units

FROM v$sql,v$session_longops

WHERE sql_address = address AND sql_hash_value = hash_value

ORDER BY address, hash_value, child_number;


I think above query will list the details for current user.

Comments are welcome!!

View RDD contents in Python Spark?

Try this:

data = f.flatMap(lambda x: x.split(' '))
map = data.map(lambda x: (x, 1))
mapreduce = map.reduceByKey(lambda x,y: x+y)
result = mapreduce.collect()

Please note that when you run collect(), the RDD - which is a distributed data set is aggregated at the driver node and is essentially converted to a list. So obviously, it won't be a good idea to collect() a 2T data set. If all you need is a couple of samples from your RDD, use take(10).

How to run Gradle from the command line on Mac bash

./gradlew

Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. . means "current directory".

How to set TextView textStyle such as bold, italic

This is the only thing that worked for me on a OnePlus 5T configured with the OnePlus Slate™ font:

textView.setTypeface(Typeface.create(textView.getTypeface(), useBold ? Typeface.BOLD : Typeface.NORMAL));

Other methods would make it fall back to Roboto when either BOLD or NORMAL.

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

The two calls have different meanings that have nothing to do with performance; the fact that it speeds up the execution time is (or might be) just a side effect. You should understand what each of them does and not blindly include them in every program because they look like an optimization.

ios_base::sync_with_stdio(false);

This disables the synchronization between the C and C++ standard streams. By default, all standard streams are synchronized, which in practice allows you to mix C- and C++-style I/O and get sensible and expected results. If you disable the synchronization, then C++ streams are allowed to have their own independent buffers, which makes mixing C- and C++-style I/O an adventure.

Also keep in mind that synchronized C++ streams are thread-safe (output from different threads may interleave, but you get no data races).

cin.tie(NULL);

This unties cin from cout. Tied streams ensure that one stream is flushed automatically before each I/O operation on the other stream.

By default cin is tied to cout to ensure a sensible user interaction. For example:

std::cout << "Enter name:";
std::cin >> name;

If cin and cout are tied, you can expect the output to be flushed (i.e., visible on the console) before the program prompts input from the user. If you untie the streams, the program might block waiting for the user to enter their name but the "Enter name" message is not yet visible (because cout is buffered by default, output is flushed/displayed on the console only on demand or when the buffer is full).

So if you untie cin from cout, you must make sure to flush cout manually every time you want to display something before expecting input on cin.

In conclusion, know what each of them does, understand the consequences, and then decide if you really want or need the possible side effect of speed improvement.

Javascript Image Resize

function resize_image(image, w, h) {

    if (typeof(image) != 'object') image = document.getElementById(image);

    if (w == null || w == undefined)
        w = (h / image.clientHeight) * image.clientWidth;

    if (h == null || h == undefined)
        h = (w / image.clientWidth) * image.clientHeight;

    image.style['height'] = h + 'px';
    image.style['width'] = w + 'px';
    return;
}

just pass it either an img DOM element, or the id of an image element, and the new width and height.

or you can pass it either just the width or just the height (if just the height, then pass the width as null or undefined) and it will resize keeping aspect ratio

Should I use SVN or Git?

The funny thing is: I host projects in Subversion Repos, but access them via the Git Clone command.

Please read Develop with Git on a Google Code Project

Although Google Code natively speaks Subversion, you can easily use Git during development. Searching for "git svn" suggests this practice is widespread, and we too encourage you to experiment with it.

Using Git on a Svn Repository gives me benefits:

  1. I can work distributed on several machines, commiting and pulling from and to them
  2. I have a central backup/public svn repository for others to check out
  3. And they are free to use Git for their own

Android Button Onclick

Use something like this :

   public void onClick(View v) {
            // TODO Auto-generated method stub
           startActivity(new Intent("com.droidnova.android.splashscreen.MyApp"));
        }

How to printf long long

    // acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2 
    double pi = 2 * acos(0.0);
    int n; // upto 6 digit
    scanf("%d",&n); //precision with which you want the value of pi
    printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision

Twitter bootstrap hide element on small devices

For Bootstrap 4.0 there is a change

See the docs: https://getbootstrap.com/docs/4.0/utilities/display/

In order to hide the content on mobile and display on the bigger devices you have to use the following classes:

d-none d-sm-block

The first class set display none all across devices and the second one display it for devices "sm" up (you could use md, lg, etc. instead of sm if you want to show on different devices.

I suggest to read about that before migration:

https://getbootstrap.com/docs/4.0/migration/#responsive-utilities

SQL Server : SUM() of multiple rows including where clauses

you mean getiing sum(Amount of all types) for each property where EndDate is null:

SELECT propertyId, SUM(Amount) as TOTAL_COSTS
  FROM MyTable
 WHERE EndDate IS NULL
GROUP BY propertyId

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0] 

How can I pass arguments to anonymous functions in JavaScript?

By removing the parameter from the anonymous function will be available in the body.

    myButton.onclick = function() { alert(myMessage); };

For more info search for 'javascript closures'

What's the difference between .bashrc, .bash_profile, and .environment?

I found information about .bashrc and .bash_profile here to sum it up:

.bash_profile is executed when you login. Stuff you put in there might be your PATH and other important environment variables.

.bashrc is used for non login shells. I'm not sure what that means. I know that RedHat executes it everytime you start another shell (su to this user or simply calling bash again) You might want to put aliases in there but again I am not sure what that means. I simply ignore it myself.

.profile is the equivalent of .bash_profile for the root. I think the name is changed to let other shells (csh, sh, tcsh) use it as well. (you don't need one as a user)

There is also .bash_logout wich executes at, yeah good guess...logout. You might want to stop deamons or even make a little housekeeping . You can also add "clear" there if you want to clear the screen when you log out.

Also there is a complete follow up on each of the configurations files here

These are probably even distro.-dependant, not all distros choose to have each configuraton with them and some have even more. But when they have the same name, they usualy include the same content.

Display / print all rows of a tibble (tbl_df)

I prefer to turn the tibble to data.frame. It shows everything and you're done

df %>% data.frame 

"Can't find Project or Library" for standard VBA functions

I have seen errors on standard functions if there was a reference to a totally different library missing.

In the VBA editor launch the Compile command from the menu and then check the References dialog to see if there is anything missing and if so try to add these libraries.

In general it seems to be good practice to compile the complete VBA code and then saving the document before distribution.

Generate GUID in MySQL for existing Data?

I faced mostly the same issue. Im my case uuid is stored as BINARY(16) and has NOT NULL UNIQUE constraints. And i faced with the issue when the same UUID was generated for every row, and UNIQUE constraint does not allow this. So this query does not work:

UNHEX(REPLACE(uuid(), '-', ''))

But for me it worked, when i used such a query with nested inner select:

UNHEX(REPLACE((SELECT uuid()), '-', ''))

Then is produced unique result for every entry.

JSON Structure for List of Objects

The first one is invalid syntax. You cannot have object properties inside a plain array. The second one is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.

This tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.

Masking password input from the console : Java

A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)

import java.io.Console;
public class Main {

    public void passwordExample() {        
        Console console = System.console();
        if (console == null) {
            System.out.println("Couldn't get Console instance");
            System.exit(0);
        }

        console.printf("Testing password%n");
        char[] passwordArray = console.readPassword("Enter your secret password: ");
        console.printf("Password entered was: %s%n", new String(passwordArray));

    }

    public static void main(String[] args) {
        new Main().passwordExample();
    }
}

Laravel 5.1 API Enable Cors

barryvdh/laravel-cors works perfectly with Laravel 5.1 with just a few key points in enabling it.

  1. After adding it as a composer dependency, make sure you have published the CORS config file and adjusted the CORS headers as you want them. Here is how mine look in app/config/cors.php

    <?php
    
    return [
    
        'supportsCredentials' => true,
        'allowedOrigins' => ['*'],
        'allowedHeaders' => ['*'],
        'allowedMethods' => ['GET', 'POST', 'PUT',  'DELETE'],
        'exposedHeaders' => ['DAV', 'content-length', 'Allow'],
        'maxAge' => 86400,
        'hosts' => [],
    ];
    
  2. After this, there is one more step that's not mentioned in the documentation, you have to add the CORS handler 'Barryvdh\Cors\HandleCors' in the App kernel. I prefer to use it in the global middleware stack. Like this

    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
    
        'Barryvdh\Cors\HandleCors',
    
    ];
    

    But its up to you to use it as a route middleware and place on specific routes.

This should make the package work with L5.1

How to add a custom HTTP header to every WCF call?

A bit late to the party but Juval Lowy addresses this exact scenario in his book and the associated ServiceModelEx library.

Basically he defines ClientBase and ChannelFactory specialisations that allow specifying type-safe header values. I suggesst downloading the source and looking at the HeaderClientBase and HeaderChannelFactory classes.

John

Javascript - removing undefined fields from an object

Another Javascript Solution

for(var i=0,keys = Object.keys(obj),len=keys.length;i<len;i++){ 
  if(typeof obj[keys[i]] === 'undefined'){
    delete obj[keys[i]];
  }
}

No additional hasOwnProperty check is required as Object.keys does not look up the prototype chain and returns only the properties of obj.

DEMO

How to update a record using sequelize for node?

I did it like this:

Model.findOne({
    where: {
      condtions
    }
  }).then( j => {
    return j.update({
      field you want to update
    }).then( r => {
      return res.status(200).json({msg: 'succesfully updated'});
    }).catch(e => {
      return res.status(400).json({msg: 'error ' +e});
    })
  }).catch( e => {
    return res.status(400).json({msg: 'error ' +e});
  });

How to split a number into individual digits in c#?

Here is some code that might help you out. Strings can be treated as an array of characters

string numbers = "12345";
int[] intArray = new int[numbers.Length];
for (int i=0; i < numbers.Length; i++)
{
   intArray[i] = int.Parse(numbers[i]);
}

How to sort List of objects by some property

You can call Collections.sort() and pass in a Comparator which you need to write to compare different properties of the object.

How to change the default collation of a table?

may need to change the SCHEMA not only table

ALTER SCHEMA `<database name>`  DEFAULT CHARACTER SET utf8mb4  DEFAULT COLLATE utf8mb4_unicode_ci (as Rich said - utf8mb4);

(mariaDB 10)

Syntax error on print with Python 3

It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.

print('Hello world!')

Explanation of <script type = "text/template"> ... </script>

It's legit and very handy!

Try this:

<script id="hello" type="text/template">
  Hello world
</script>
<script>
  alert($('#hello').html());
</script>

Several Javascript templating libraries use this technique. Handlebars.js is a good example.

Integrating the ZXing library directly into my Android application

If you just need the core.jar from zxing, you can skip that process and get the pre-built JARs from the GettingStarted wiki page

Latest ZXing (2.2) doesn't have core.jar under core folder but you can obtain the core.jar from the zxing Maven repository here

Set up a scheduled job?

after the part of code,I can write anything just like my views.py :)

#######################################
import os,sys
sys.path.append('/home/administrator/development/store')
os.environ['DJANGO_SETTINGS_MODULE']='store.settings'
from django.core.management impor setup_environ
from store import settings
setup_environ(settings)
#######################################

from http://www.cotellese.net/2007/09/27/running-external-scripts-against-django-models/

What difference does .AsNoTracking() make?

AsNoTracking() allows the "unique key per record" requirement in EF to be bypassed (not mentioned explicitly by other answers).

This is extremely helpful when reading a View that does not support a unique key because perhaps some fields are nullable or the nature of the view is not logically indexable.

For these cases the "key" can be set to any non-nullable column but then AsNoTracking() must be used with every query else records (duplicate by key) will be skipped.

Swift: Sort array of objects alphabetically

In the closure you pass to sort, compare the properties you want to sort by. Like this:

movieArr.sorted { $0.name < $1.name }

or the following in the cases that you want to bypass cases:

movieArr.sorted { $0.name.lowercased() < $1.name.lowercased() }

Sidenote: Typically only types start with an uppercase letter; I'd recommend using name and date, not Name and Date.


Example, in a playground:

class Movie {
    let name: String
    var date: Int?

    init(_ name: String) {
        self.name = name
    }
}

var movieA = Movie("A")
var movieB = Movie("B")
var movieC = Movie("C")

let movies = [movieB, movieC, movieA]
let sortedMovies = movies.sorted { $0.name < $1.name }
sortedMovies

sortedMovies will be in the order [movieA, movieB, movieC]

Swift5 Update

channelsArray = channelsArray.sorted { (channel1, channel2) -> Bool in
            let channelName1 = channel1.name
            let channelName2 = channel2.name
            return (channelName1.localizedCaseInsensitiveCompare(channelName2) == .orderedAscending)

@RequestParam vs @PathVariable

1) @RequestParam is used to extract query parameters

http://localhost:3000/api/group/test?id=4

@GetMapping("/group/test")
public ResponseEntity<?> test(@RequestParam Long id) {
    System.out.println("This is test");
    return ResponseEntity.ok().body(id);
}

while @PathVariable is used to extract data right from the URI:

http://localhost:3000/api/group/test/4

@GetMapping("/group/test/{id}")
public ResponseEntity<?> test(@PathVariable Long id) {
    System.out.println("This is test");
    return ResponseEntity.ok().body(id);
}

2) @RequestParam is more useful on a traditional web application where data is mostly passed in the query parameters while @PathVariable is more suitable for RESTful web services where URL contains values.

3) @RequestParam annotation can specify default values if a query parameter is not present or empty by using a defaultValue attribute, provided the required attribute is false:

@RestController
@RequestMapping("/home")
public class IndexController {

    @RequestMapping(value = "/name")
    String getName(@RequestParam(value = "person", defaultValue = "John") String personName) {
        return "Required element of request param";
    }

}

How to pass variable number of arguments to a PHP function

Since PHP 5.6, a variable argument list can be specified with the ... operator.

function do_something($first, ...$all_the_others)
{
    var_dump($first);
    var_dump($all_the_others);
}

do_something('this goes in first', 2, 3, 4, 5);

#> string(18) "this goes in first"
#>
#> array(4) {
#>   [0]=>
#>   int(2)
#>   [1]=>
#>   int(3)
#>   [2]=>
#>   int(4)
#>   [3]=>
#>   int(5)
#> }

As you can see, the ... operator collects the variable list of arguments in an array.

If you need to pass the variable arguments to another function, the ... can still help you.

function do_something($first, ...$all_the_others)
{
    do_something_else($first, ...$all_the_others);
    // Which is translated to:
    // do_something_else('this goes in first', 2, 3, 4, 5);
}

Since PHP 7, the variable list of arguments can be forced to be all of the same type too.

function do_something($first, int ...$all_the_others) { /**/ }

How can I disable ARC for a single file in a project?

  1. select project -> targets -> build phases -> compiler sources
  2. select file -> compiler flags
  3. add -fno-objc-arc

Read JSON data in a shell script

There is jq for parsing json on the command line:

 jq '.Body'

Visit this for jq: https://stedolan.github.io/jq/

Convert object string to JSON

Disclaimer: don't try this at home, or for anything that requires other devs taking you seriously:

JSON.stringify(eval('(' + str + ')'));

There, I did it.
Try not to do it tho, eval is BAD for you. As told above, use Crockford's JSON shim for older browsers (IE7 and under)

This method requires your string to be valid javascript, which will be converted to a javascript object that can then be serialized to JSON.

edit: fixed as Rocket suggested.

Create a symbolic link of directory in Ubuntu

This is the behavior of ln if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx to be the symlink, you should remove that directory first and run that same command.

ngrok command not found

For Linux :https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip

For Mac :https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip

For Windows:https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip

unzip it for linux and mac users move file to /usr/local/bin and execute ngrok http 80 command in the terminal

I don't have any idea about windows

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

I have perfect answer for all this : I tried so many solution not able to get finally myself able to manage , please find detail answer below:

       $.ajax({
            traditional: true,
            url: "/Conroller/MethodTest",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data:JSON.stringify( 
               [
                { id: 1, color: 'yellow' },
                { id: 2, color: 'blue' },
                { id: 3, color: 'red' }
                ]),
            success: function (data) {
                $scope.DisplayError(data.requestStatus);
            }
        });

Controler

public class Thing
{
    public int id { get; set; }
    public string color { get; set; }
}

public JsonResult MethodTest(IEnumerable<Thing> datav)
    {
   //now  datav is having all your values
  }

Git Commit Messages: 50/72 Formatting

I'd agree it is interesting to propose a particular style of working. However, unless I have the chance to set the style, I usually follow what's been done for consistency.

Taking a look at the Linux Kernel Commits, the project that started git if you like, http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=bca476139d2ded86be146dae09b06e22548b67f3, they don't follow the 50/72 rule. The first line is 54 characters.

I would say consistency matters. Set up proper means of identifying users who've made commits (user.name, user.email - especially on internal networks. User@OFFICE-1-PC-10293982811111 isn't a useful contact address). Depending on the project, make the appropriate detail available in the commit. It's hard to say what that should be; it might be tasks completed in a development process, then details of what's changed.

I don't believe users should use git one way because certain interfaces to git treat the commits in certain ways.

I should also note there are other ways to find commits. For a start, git diff will tell you what's changed. You can also do things like git log --pretty=format:'%T %cN %ce' to format the options of git log.

How to clear Facebook Sharer cache?

Append a ?v=random_string to the url. If you are using this idea with Facebook share, make sure that the og:url param in the response matches the url you are sharing. This will work with google plus too.

For Facebook, you can also force recrawl by making a post request to https://graph.facebook.com

{id: url,
scrape: true}

Target class controller does not exist - Laravel 8

For solution just uncomment line 29:

**protected $namespace = 'App\\Http\\Controllers';**

in 'app\Providers\RouteServiceProvider.php' file.

just uncomment line 29

The identity used to sign the executable is no longer valid

This answer is exactly work for me .


146 down vote Neither restarting Xcode nor restarting my Mac helped.

Solution within Xcode:

In Xcode, go to Preferences --> Accounts --> View Details
Press the + symbol and select iOS Development
Press the refresh button in the lower left corner (called Download all in Xcode 7)

PS:

Sometimes it may also help to delete invalid provisioning profiles: right-click -> move to trash
I saw this error exactly one year after signing up as an Apple developer.

*** What I want to know is why this problem occur frequently after November ? ps:My Apple Developer Account has been signing up several years.But this year I have changed Agent role to another e-mail account.

Total size of the contents of all the files in a directory

When a folder is created, many Linux filesystems allocate 4096 bytes to store some metadata about the directory itself. This space is increased by a multiple of 4096 bytes as the directory grows.

du command (with or without -b option) take in count this space, as you can see typing:

mkdir test && du -b test

you will have a result of 4096 bytes for an empty dir. So, if you put 2 files of 10000 bytes inside the dir, the total amount given by du -sb would be 24096 bytes.

If you read carefully the question, this is not what asked. The questioner asked:

the sum total of all the data in files and subdirectories I would get if I opened each file and counted the bytes

that in the example above should be 20000 bytes, not 24096.

So, the correct answer IMHO could be a blend of Nelson answer and hlovdal suggestion to handle filenames containing spaces:

find . -type f -print0 | xargs -0 stat --format=%s | awk '{s+=$1} END {print s}'

How to generate random number in Bash?

Wanted to use /dev/urandom without dd and od

function roll() { local modulus=${1:-6}; echo $(( 1 + 0x$(env LC_CTYPE=C tr -dc '0-9a-fA-F' < /dev/urandom | head -c5 ) % $modulus )); }

Testing

$ roll
5
$ roll 12
12

Just how random is it?

$ (echo "count roll percentage"; i=0; while [ $i -lt 10000 ]; do roll; i=$((i+1)); done | sort | uniq -c | awk '{print $0,($1/10000*100)"%"}') | column -t
count  roll  percentage
1625   1     16.25%
1665   2     16.65%
1646   3     16.46%
1720   4     17.2%
1694   5     16.94%
1650   6     16.5%

View the change history of a file using Git versioning

If you're using the git GUI (on Windows) under the Repository menu you can use "Visualize master's History". Highlight a commit in the top pane and a file in the lower right and you'll see the diff for that commit in the lower left.

jQuery ajax error function

Try this:

error: function(jqXHR, textStatus, errorThrown) {
  console.log(textStatus, errorThrown);
}

If you want to inform your frontend about a validation error, try to return json:

dataType: 'json',
success: function(data, textStatus, jqXHR) {
   console.log(data.error);
}

Your asp script schould return:

{"error": true}

__FILE__ macro shows full path

A short, working answer for both Windows and *nix:

#define __FILENAME__ std::max<const char*>(__FILE__,\
    std::max(strrchr(__FILE__, '\\')+1, strrchr(__FILE__, '/')+1))

How can I time a code segment for testing performance with Pythons timeit?

I see the question has already been answered, but still want to add my 2 cents for the same.

I have also faced similar scenario in which I have to test the execution times for several approaches and hence written a small script, which calls timeit on all functions written in it.

The script is also available as github gist here.

Hope it will help you and others.

from random import random
import types

def list_without_comprehension():
    l = []
    for i in xrange(1000):
        l.append(int(random()*100 % 100))
    return l

def list_with_comprehension():
    # 1K random numbers between 0 to 100
    l = [int(random()*100 % 100) for _ in xrange(1000)]
    return l


# operations on list_without_comprehension
def sort_list_without_comprehension():
    list_without_comprehension().sort()

def reverse_sort_list_without_comprehension():
    list_without_comprehension().sort(reverse=True)

def sorted_list_without_comprehension():
    sorted(list_without_comprehension())


# operations on list_with_comprehension
def sort_list_with_comprehension():
    list_with_comprehension().sort()

def reverse_sort_list_with_comprehension():
    list_with_comprehension().sort(reverse=True)

def sorted_list_with_comprehension():
    sorted(list_with_comprehension())


def main():
    objs = globals()
    funcs = []
    f = open("timeit_demo.sh", "w+")

    for objname in objs:
        if objname != 'main' and type(objs[objname]) == types.FunctionType:
            funcs.append(objname)
    funcs.sort()
    for func in funcs:
        f.write('''echo "Timing: %(funcname)s"
python -m timeit "import timeit_demo; timeit_demo.%(funcname)s();"\n\n
echo "------------------------------------------------------------"
''' % dict(
                funcname = func,
                )
            )

    f.close()

if __name__ == "__main__":
    main()

    from os import system

    #Works only for *nix platforms
    system("/bin/bash timeit_demo.sh")

    #un-comment below for windows
    #system("cmd timeit_demo.sh")

How to get a resource id with a known resource name?

// image from res/drawable
    int resID = getResources().getIdentifier("my_image", 
            "drawable", getPackageName());
// view
    int resID = getResources().getIdentifier("my_resource", 
            "id", getPackageName());

// string
    int resID = getResources().getIdentifier("my_string", 
            "string", getPackageName());

How to solve "The directory is not empty" error when running rmdir command in a batch script?

Windows sometimes is "broken by design", so you need to create an empty folder, and then mirror the "broken folder" with an "empty folder" with backup mode.

robocopy - cmd copy utility

/copyall - copies everything
/mir deletes item if there is no such item in source a.k.a mirrors source with
destination
/b works around premissions shenanigans

Create en empty dir like this:

mkdir empty

overwrite broken folder with empty like this:

robocopy /copyall /mir /b empty broken

and then delete that folder

rd broken /s
rd empty /s

If this does not help, try restarting in "recovery mode with command prompt" by holding shift when clicking restart and trying to run these command again in recovery mode

Easiest way to open a download window without navigating away from the page

I always add a target="_blank" to the download link. This will open a new window, but as soon as the user clicks save, the new window is closed.

Prevent users from submitting a form by hitting Enter

You can also use javascript:void(0) to prevent form submission.

<form action="javascript:void(0)" method="post">
    <label for="">Search</label>
    <input type="text">
    <button type="sybmit">Submit</button>
</form>

_x000D_
_x000D_
<form action="javascript:void(0)" method="post">_x000D_
    <label for="">Search</label>_x000D_
    <input type="text">_x000D_
    <button type="sybmit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

Select method in List<t> Collection

Generic List<T> have the Where<T>(Func<T, Boolean>) extension method that can be used to filter data.

In your case with a row array:

var rows = rowsArray.Where(row => row["LastName"].ToString().StartsWith("a"));

If you are using DataRowCollection, you need to cast it first.

var rows = dataTableRows.Cast<DataRow>().Where(row => row["LastName"].ToString().StartsWith("a"));

What does HTTP/1.1 302 mean exactly?

  • The code 302 indicates a temporary redirection.
  • One of the most notable features that differentiate it from a 301 redirect is that, in the case of 302 redirects, the strength of the SEO is not transferred to a new URL.
  • This is because this redirection has been designed to be used when there is a need to redirect content to a page that will not be the definitive one. Thus, once the redirection is eliminated, the original page will not have lost its positioning in the Google search engine.

EXAMPLE:- Although it is not very common that we find ourselves in need of a 302 redirect, this option can be very useful in some cases. These are the most frequent cases:

  • When we realize that there is some inappropriate content on a page. While we solve the problem, we can redirect the user to another page that may be of interest.
  • In the event that an attack on our website requires the restoration of any of the pages, this redirect can help us minimize the incidence.

A redirect 302 is a code that tells visitors of a specific URL that the page has been moved temporarily, directing them directly to the new location.

  • In other words, redirect 302 is activated when Google robots or other search engines request to load a specific page. At that moment, thanks to this redirection, the server returns an automatic response indicating a new URL.

  • In this way errors and annoyances are avoided both to search engines and users, guaranteeing smooth navigation.

For More details Refer this Article.

Install GD library and freetype on Linux

Things are pretty much simpler unless they are made confusing.

To Install GD library in Ubuntu

sudo apt-get install php5-gd

To Install Freetype in Ubuntu

sudo apt-get install libfreetype6-dev:i386

No Android SDK found - Android Studio

I had the same problem, Android Studio just could not identify the android-sdk folder. All I did was to uninstall and reinstall android studio, and this time it actually identified the folder. Hope it also works out for you.

Is it possible to use the SELECT INTO clause with UNION [ALL]?

This works in SQL Server:

SELECT * INTO tmpFerdeen FROM (
  SELECT top 100 * 
  FROM Customers
  UNION All
  SELECT top 100 * 
  FROM CustomerEurope
  UNION All
  SELECT top 100 * 
  FROM CustomerAsia
  UNION All
  SELECT top 100 * 
  FROM CustomerAmericas
) as tmp

Object does not support item assignment error

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

Ruby on Rails form_for select field with class

You can also add prompt option like this.

<%= f.select(:object_field, ['Item 1', 'Item 2'], {include_blank: "Select something"}, { :class => 'my_style_class' }) %>

Set space between divs

You need a gutter between two div gutter can be made as following

margin(gutter) = width - gutter size E.g margin = calc(70% - 2em)

<body bgcolor="gray">
<section id="main">
        <div id="left">
            Something here     
        </div>
        <div id="right">
                Someone there
        </div>
</section>
</body>
<style>
body{
    font-size: 10px;
}

#main div{
    float: left;
    background-color:#ffffff;
    width: calc(50% - 1.5em);
    margin-left: 1.5em;
}
</style>

How to hide form code from view code/inspect element browser?

you can not stop user from seeing our code but you can avoid it by disabling some keys

simply you can do <body oncontextmenu="return false" onkeydown="return false;" onmousedown="return false;"><!--Your body context--> </body>

After doing this following keys get disabled automatically

1. Ctrl + Shift + U 2. Ctrl + Shift + C 3. Ctrl + Shift + I 4. Right Click of mouse 5. F12 Key

Why is there an unexplainable gap between these inline-block div elements?

Using inline-block allows for white-space in your HTML, This usually equates to .25em (or 4px).

You can either comment out the white-space or, a more commons solution, is to set the parent's font-size to 0 and the reset it back to the required size on the inline-block elements.

how can I debug a jar at runtime?

You can activate JVM's debugging capability when starting up the java command with a special option:

java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=y -jar path/to/some/war/or/jar.jar

Starting up jar.jar like that on the command line will:

  • put this JVM instance in the role of a server (server=y) listening on port 8000 (address=8000)
  • write Listening for transport dt_socket at address: 8000 to stdout and
  • then pause the application (suspend=y) until some debugger connects. The debugger acts as the client in this scenario.

Common options for selecting a debugger are:

  • Eclipse Debugger: Under Run -> Debug Configurations... -> select Remote Java Application -> click the New launch configuration button. Provide an arbitrary Name for this debug configuration, Connection Type: Standard (Socket Attach) and as Connection Properties the entries Host: localhost, Port: 8000. Apply the Changes and click Debug. At the moment the Eclipse Debugger has successfully connected to the JVM, jar.jar should begin executing.
  • jdb command-line tool: Start it up with jdb -connect com.sun.jdi.SocketAttach:port=8000

Issue with adding common code as git submodule: "already exists in the index"

I had the same problem and after hours of looking found the answer.

The error I was getting was a little different: <path> already exists and is not a valid git repo (and added here for SEO value)

The solution is to NOT create the directory that will house the submodule. The directory will be created as part of the git submodule add command.

Also, the argument is expected to be relative to the parent-repo root, not your working directory, so watch out for that.

Solution for the example above:

  1. It IS okay to have your parent repo already cloned.
  2. Make sure the common_code directory does not exist.
  3. cd Repo
  4. git submodule add git://url_to_repo projectfolder/common_code/ (Note the required trailing slash.)
  5. Sanity restored.

I hope this helps someone, as there is very little information to be found elsewhere about this.

How do I count columns of a table

I think you need also to specify the name of the database:

SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'SchemaNameHere'
  AND table_name = 'TableNameHere'

if you don't specify the name of your database, chances are it will count all columns as long as it matches the name of your table. For example, you have two database: DBaseA and DbaseB, In DBaseA, it has two tables: TabA(3 fields), TabB(4 fields). And in DBaseB, it has again two tables: TabA(4 fields), TabC(4 fields).

if you run this query:

SELECT count(*)
FROM information_schema.columns
WHERE table_name = 'TabA'

it will return 7 because there are two tables named TabA. But by adding another condition table_schema = 'SchemaNameHere':

SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'DBaseA'
  AND table_name = 'TabA'

then it will only return 3.

C# Iterate through Class properties

I tried what Samuel Slade has suggested. Didn't work for me. The PropertyInfo list was coming as empty. So, I tried the following and it worked for me.

    Type type = typeof(Record);
    FieldInfo[] properties = type.GetFields();
    foreach (FieldInfo property in properties) {
       Debug.LogError(property.Name);
    }

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

The answer code allow only to localhost:8888. This code can't be deployed to the production, or different server and port name.

To get it working for all sources, use this instead:

// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

PHP - Modify current object in foreach loop

Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?

Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.

For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.

<?php

$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);

vs

<?php

$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
    $arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);

If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

What is the difference between i++ & ++i in a for loop?

Both i++ and ++i are short-hand for i = i + 1.

In addition to changing the value of i, they also return the value of i, either before adding one (i++) or after adding one (++i).

In a loop the third component is a piece of code that is executed after each iteration.

for (int i=0; i<10; i++)

The value of that part is not used, so the above is just the same as

for(int i=0; i<10; i = i+1)

or

for(int i=0; i<10; ++i)

Where it makes a difference (between i++ and ++i )is in these cases

while(i++ < 10)

for (int i=0; i++ < 10; )

Why does background-color have no effect on this DIV?

Floats don't have a height so the containing div has a height of zero.

<div style="background-color:black; overflow:hidden;zoom:1" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

overflow:hidden clears the float for most browsers.

zoom:1 clears the float for IE.

How do I encode/decode HTML entities in Ruby?

I think Nokogiri gem is also a good choice. It is very stable and has a huge contributing community.

Samples:

a = Nokogiri::HTML.parse "foo&nbsp;b&auml;r"    
a.text 
=> "foo bär"

or

a = Nokogiri::HTML.parse "&iexcl;I&#39;m highly&nbsp;annoyed with character references!"
a.text
=> "¡I'm highly annoyed with character references!"

Rollback to last git commit

An easy foolproof way to UNDO local file changes since the last commit is to place them in a new branch:

git branch changes
git checkout changes
git add .
git commit

This leaves the changes in the new branch. Return to the original branch to find it back to the last commit:

git checkout master

The new branch is a good place to practice different ways to revert changes without risk of messing up the original branch.

Setting font on NSAttributedString on UITextView disregards line spacing

There was a bug in iOS 6, that causes line height to be ignored when font is set. See answer to NSParagraphStyle line spacing ignored and longer bug analysis at Radar: UITextView Ignores Minimum/Maximum Line Height in Attributed String.

How to apply font anti-alias effects in CSS?

Short answer: You can't.

CSS does not have techniques which affect the rendering of fonts in the browser; only the system can do that.

Obviously, text sharpness can easily be achieved with pixel-dense screens, but if you're using a normal PC that's gonna be hard to achieve.

There are some newer fonts that are smooth but at the sacrifice of it appearing somewhat blurry (look at most of Adobe's fonts, for example). You can also find some smooth-but-blurry-by-design fonts at Google Fonts, however.

There are some new CSS3 techniques for font rendering and text effects though the consistency, performance, and reliability of these techniques vary so largely to the point where you generally shouldn't rely on them too much.

How to query DATETIME field using only date in Microsoft SQL Server?

use range, or DateDiff function

 select * from test 
 where date between '03/19/2014' and '03/19/2014 23:59:59'

or

 select * from test 
 where datediff(day, date, '03/19/2014') = 0

Other options are:

  1. If you have control over the database schema, and you don't need the time data, take it out.

  2. or, if you must keep it, add a computed column attribute that has the time portion of the date value stripped off...

Alter table Test Add DateOnly As DateAdd(day, datediff(day, 0, date), 0)

or, in more recent versions of SQL Server...

Alter table Test Add DateOnly As Cast(DateAdd(day, datediff(day, 0, date), 0) as Date)

then, you can write your query as simply:

select * from test 
where DateOnly = '03/19/2014'

Insert array into MySQL database with PHP

most easiest way

for ($i=0; $i < count($tableData); $i++) { 

        $cost     =$tableData[$i]['cost'];
        $quantity =$tableData[$i]['quantity'];
        $price    =$tableData[$i]['price'];
        $p_id     =$tableData[$i]['p_id'];

        mysqli_query($conn,"INSERT INTO bill_details (bill_id, price, bill_date, p_id, quantity, cost) VALUES ($bill_id[bill_id],$price,$date,$p_id,$quantity,$cost)");
    }

How do I pass multiple parameter in URL?

I do not know much about Java but URL query arguments should be separated by "&", not "?"

http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.

Git Pull vs Git Rebase

git-pull - Fetch from and integrate with another repository or a local branch GIT PULL

Basically you are pulling remote branch to your local, example:

git pull origin master

Will pull master branch into your local repository

git-rebase - Forward-port local commits to the updated upstream head GIT REBASE

This one is putting your local changes on top of changes done remotely by other users. For example:

  • You have committed some changes on your local branch for example called SOME-FEATURE
  • Your friend in the meantime was working on other features and he merged his branch into master

Now you want to see his and your changes on your local branch. So then you checkout master branch:

git checkout master

then you can pull:

git pull origin master

and then you go to your branch:

git checkout SOME-FEATURE

and you can do rebase master to get lastest changes from it and put your branch commits on top:

git rebase master

I hope now it's a bit more clear for you.

How do I get the row count of a Pandas DataFrame?

Suppose df is your dataframe then:

count_row = df.shape[0]  # Gives number of rows
count_col = df.shape[1]  # Gives number of columns

Or, more succinctly,

r, c = df.shape

Password Protect a SQLite DB. Is it possible?

You can encrypt your SQLite database with the SEE addon. This way you prevent unauthorized access/modification.

Quoting SQLite documentation:

The SQLite Encryption Extension (SEE) is an enhanced version of SQLite that encrypts database files using 128-bit or 256-Bit AES to help prevent unauthorized access or modification. The entire database file is encrypted so that to an outside observer, the database file appears to contain white noise. There is nothing that identifies the file as an SQLite database.

You can find more info about this addon in this link.

Cross browser method to fit a child div to its parent's width

If you put position:relative; on the outer element, the inner element will place itself according to this one. Then a width:auto; on the inner element will be the same as the width of the outer.

Get current URL/URI without some of $_GET variables

Yii 1

Most of the other answers are wrong. The poster is asking for the url WITHOUT (some) $_GET-parameters.

Here is a complete breakdown (creating url for the currently active controller, modules or not):

// without $_GET-parameters
Yii::app()->controller->createUrl(Yii::app()->controller->action->id);

// with $_GET-parameters, HAVING ONLY supplied keys
Yii::app()->controller->createUrl(Yii::app()->controller->action->id,
    array_intersect_key($_GET, array_flip(['id']))); // include 'id'

// with all $_GET-parameters, EXCEPT supplied keys
Yii::app()->controller->createUrl(Yii::app()->controller->action->id,
    array_diff_key($_GET, array_flip(['lg']))); // exclude 'lg'

// with ALL $_GET-parameters (as mensioned in other answers)
Yii::app()->controller->createUrl(Yii::app()->controller->action->id, $_GET);
Yii::app()->request->url;

When you don't have the same active controller, you have to specify the full path like this:

Yii::app()->createUrl('/controller/action');
Yii::app()->createUrl('/module/controller/action');

Check out the Yii guide for building url's in general: http://www.yiiframework.com/doc/guide/1.1/en/topics.url#creating-urls

How do I populate a JComboBox with an ArrayList?

I believe you can create a new Vector using your ArrayList and pass that to the JCombobox Constructor.

JComboBox<String> combobox = new JComboBox<String>(new Vector<String>(myArrayList));

my example is only strings though.

SQL Server date format yyyymmdd

try this....

SELECT FORMAT(CAST(DOB AS DATE),'yyyyMMdd') FROM Employees;

Removing spaces from string

Try this:

String urle = HOST + url + value;

Then return the values from:

urle.replace(" ", "%20").trim();

Convert a String of Hex into ASCII in Java

To this case, I have a hexadecimal data format into an int array and I want to convert them on String.

int[] encodeHex = new int[] { 0x48, 0x65, 0x6c, 0x6c, 0x6f }; // Hello encode
for (int i = 0; i < encodeHex.length; i++) {
   System.out.print((char) (encodeHex[i]));
}

MySQL user DB does not have password columns - Installing MySQL on OSX

remember password needs to be set further even after restarting mysql as below

SET PASSWORD = PASSWORD('root');

Error in file(file, "rt") : cannot open the connection

Got this error and found that RStudio on my Windows machine try to use \ as escape symbol, so had to replace it with \\ to deal with it.

Try file.exists function with your path, e.g.:

file.exists("D:\\R\\path_to_file.csv")

Efficiently updating database using SQLAlchemy ORM

Here's an example of how to solve the same problem without having to map the fields manually:

from sqlalchemy import Column, ForeignKey, Integer, String, Date, DateTime, text, create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.attributes import InstrumentedAttribute

engine = create_engine('postgres://postgres@localhost:5432/database')
session = sessionmaker()
session.configure(bind=engine)

Base = declarative_base()


class Media(Base):
  __tablename__ = 'media'
  id = Column(Integer, primary_key=True)
  title = Column(String, nullable=False)
  slug = Column(String, nullable=False)
  type = Column(String, nullable=False)

  def update(self):
    s = session()
    mapped_values = {}
    for item in Media.__dict__.iteritems():
      field_name = item[0]
      field_type = item[1]
      is_column = isinstance(field_type, InstrumentedAttribute)
      if is_column:
        mapped_values[field_name] = getattr(self, field_name)

    s.query(Media).filter(Media.id == self.id).update(mapped_values)
    s.commit()

So to update a Media instance, you can do something like this:

media = Media(id=123, title="Titular Line", slug="titular-line", type="movie")
media.update()

How to write Unicode characters to the console?

This works for me:

Console.OutputEncoding = System.Text.Encoding.Default;

To display some of the symbols, it's required to set Command Prompt's font to Lucida Console:

  1. Open Command Prompt;

  2. Right click on the top bar of the Command Prompt;

  3. Click Properties;

  4. If the font is set to Raster Fonts, change it to Lucida Console.

SQL Server: Maximum character length of object names

You can also use this script to figure out more info:

EXEC sp_server_info

The result will be something like that:

attribute_id | attribute_name        | attribute_value
-------------|-----------------------|-----------------------------------
           1 | DBMS_NAME             | Microsoft SQL Server
           2 | DBMS_VER              | Microsoft SQL Server 2012 - 11.0.6020.0
          10 | OWNER_TERM            | owner
          11 | TABLE_TERM            | table
          12 | MAX_OWNER_NAME_LENGTH | 128
          13 | TABLE_LENGTH          | 128
          14 | MAX_QUAL_LENGTH       | 128
          15 | COLUMN_LENGTH         | 128
          16 | IDENTIFIER_CASE       | MIXED
           ?  ?                       ?
           ?  ?                       ?
           ?  ?                       ?

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

From Twitter Bootstrap documentation:

  • small grid (= 768px) = .col-sm-*,
  • medium grid (= 992px) = .col-md-*,
  • large grid (= 1200px) = .col-lg-*.

to Read More...

Finding local IP addresses using Python's stdlib

If you don't want to use external packages and don't want to rely on outside Internet servers, this might help. It's a code sample that I found on Google Code Search and modified to return required information:

def getIPAddresses():
    from ctypes import Structure, windll, sizeof
    from ctypes import POINTER, byref
    from ctypes import c_ulong, c_uint, c_ubyte, c_char
    MAX_ADAPTER_DESCRIPTION_LENGTH = 128
    MAX_ADAPTER_NAME_LENGTH = 256
    MAX_ADAPTER_ADDRESS_LENGTH = 8
    class IP_ADDR_STRING(Structure):
        pass
    LP_IP_ADDR_STRING = POINTER(IP_ADDR_STRING)
    IP_ADDR_STRING._fields_ = [
        ("next", LP_IP_ADDR_STRING),
        ("ipAddress", c_char * 16),
        ("ipMask", c_char * 16),
        ("context", c_ulong)]
    class IP_ADAPTER_INFO (Structure):
        pass
    LP_IP_ADAPTER_INFO = POINTER(IP_ADAPTER_INFO)
    IP_ADAPTER_INFO._fields_ = [
        ("next", LP_IP_ADAPTER_INFO),
        ("comboIndex", c_ulong),
        ("adapterName", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)),
        ("description", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)),
        ("addressLength", c_uint),
        ("address", c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH),
        ("index", c_ulong),
        ("type", c_uint),
        ("dhcpEnabled", c_uint),
        ("currentIpAddress", LP_IP_ADDR_STRING),
        ("ipAddressList", IP_ADDR_STRING),
        ("gatewayList", IP_ADDR_STRING),
        ("dhcpServer", IP_ADDR_STRING),
        ("haveWins", c_uint),
        ("primaryWinsServer", IP_ADDR_STRING),
        ("secondaryWinsServer", IP_ADDR_STRING),
        ("leaseObtained", c_ulong),
        ("leaseExpires", c_ulong)]
    GetAdaptersInfo = windll.iphlpapi.GetAdaptersInfo
    GetAdaptersInfo.restype = c_ulong
    GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, POINTER(c_ulong)]
    adapterList = (IP_ADAPTER_INFO * 10)()
    buflen = c_ulong(sizeof(adapterList))
    rc = GetAdaptersInfo(byref(adapterList[0]), byref(buflen))
    if rc == 0:
        for a in adapterList:
            adNode = a.ipAddressList
            while True:
                ipAddr = adNode.ipAddress
                if ipAddr:
                    yield ipAddr
                adNode = adNode.next
                if not adNode:
                    break

Usage:

>>> for addr in getIPAddresses():
>>>    print addr
192.168.0.100
10.5.9.207

As it relies on windll, this will work only on Windows.

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

As johnnyynnoj mentioned ng-repeat creates a new scope. I would in fact use a function to set the value. See plunker

JS:

$scope.setSelected = function(selected) {
  $scope.selected = selected;
}

HTML:

{{ selected }}

<ul>
  <li ng-class="{current: selected == 100}">
     <a href ng:click="setSelected(100)">ABC</a>
  </li>
  <li ng-class="{current: selected == 101}">
     <a href ng:click="setSelected(101)">DEF</a>
  </li>
  <li ng-class="{current: selected == $index }" 
      ng-repeat="x in [4,5,6,7]">
     <a href ng:click="setSelected($index)">A{{$index}}</a>
  </li>
</ul>

<div  
  ng:show="selected == 100">
  100        
</div>
<div  
  ng:show="selected == 101">
  101        
</div>
<div ng-repeat="x in [4,5,6,7]" 
  ng:show="selected == $index">
  {{ $index }}        
</div>

C# code to validate email address

I use this single liner method which does the work for me-

using System.ComponentModel.DataAnnotations;
public bool IsValidEmail(string source)
{
    return new EmailAddressAttribute().IsValid(source);
}

Per the comments, this will "fail" if the source (the email address) is null.

public static bool IsValidEmailAddress(this string address) => address != null && new EmailAddressAttribute().IsValid(address);

Convert.ToDateTime: how to set format

How about this:

    string test = "01-12-12";
    try{
         DateTime dateTime = DateTime.Parse(test);
         test = dateTime.ToString("dd/yyyy");
    }
    catch (FormatException exc)
    {
        MessageBox.Show(exc.Message);
    }

Where test will be equal to "12/2012"

Hope it helps!

Please read HERE.

Store JSON object in data attribute in HTML jQuery

!DOCTYPE html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$("#btn1").click(function()
{
person = new Object();
person.name = "vishal";
person.age =20;
    $("div").data(person);
});
  $("#btn2").click(function()
{
    alert($("div").data("name"));
});

});

</script>
<body>
<button id="btn1">Attach data to div element</button><br>
<button id="btn2">Get data attached to div element</button>
<div></div>
</body>


</html>

Anser:-Attach data to selected elements using an object with name/value pairs.
GET value using object propetis like name,age etc...

Get last key-value pair in PHP array

$last = array_slice($array, -1, 1, true);

See http://php.net/array_slice for details on what the arguments mean.

P.S. Unlike the other answers, this one actually does what you want. :-)

Ideal way to cancel an executing AsyncTask

I don't like to force interrupt my async tasks with cancel(true) unnecessarily because they may have resources to be freed, such as closing sockets or file streams, writing data to the local database etc. On the other hand, I have faced situations in which the async task refuses to finish itself part of the time, for example sometimes when the main activity is being closed and I request the async task to finish from inside the activity's onPause() method. So it's not a matter of simply calling running = false. I have to go for a mixed solution: both call running = false, then giving the async task a few milliseconds to finish, and then call either cancel(false) or cancel(true).

if (backgroundTask != null) {
    backgroundTask.requestTermination();
    try {
        Thread.sleep((int)(0.5 * 1000));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    if (backgroundTask.getStatus() != AsyncTask.Status.FINISHED) {
        backgroundTask.cancel(false);
    }
    backgroundTask = null;
}

As a side result, after doInBackground() finishes, sometimes the onCancelled() method is called, and sometimes onPostExecute(). But at least the async task termination is guaranteed.

Pandas/Python: Set value of one column based on value in another column

one way to do this would be to use indexing with .loc.

Example

In the absence of an example dataframe, I'll make one up here:

import numpy as np
import pandas as pd

df = pd.DataFrame({'c1': list('abcdefg')})
df.loc[5, 'c1'] = 'Value'

>>> df
      c1
0      a
1      b
2      c
3      d
4      e
5  Value
6      g

Assuming you wanted to create a new column c2, equivalent to c1 except where c1 is Value, in which case, you would like to assign it to 10:

First, you could create a new column c2, and set it to equivalent as c1, using one of the following two lines (they essentially do the same thing):

df = df.assign(c2 = df['c1'])
# OR:
df['c2'] = df['c1']

Then, find all the indices where c1 is equal to 'Value' using .loc, and assign your desired value in c2 at those indices:

df.loc[df['c1'] == 'Value', 'c2'] = 10

And you end up with this:

>>> df
      c1  c2
0      a   a
1      b   b
2      c   c
3      d   d
4      e   e
5  Value  10
6      g   g

If, as you suggested in your question, you would perhaps sometimes just want to replace the values in the column you already have, rather than create a new column, then just skip the column creation, and do the following:

df['c1'].loc[df['c1'] == 'Value'] = 10
# or:
df.loc[df['c1'] == 'Value', 'c1'] = 10

Giving you:

>>> df
      c1
0      a
1      b
2      c
3      d
4      e
5     10
6      g

Completely Remove MySQL Ubuntu 14.04 LTS

I experienced a similar issue on Ubuntu 14.04 LTS after a MySQL update.

I started getting error: "Fatal error: Can't open and lock privilege tables: Incorrect file format 'user'" in /var/log/mysql/error.log

MySQL could not start.

I resolved it by removing the following directory: /var/lib/mysql/mysql

sudo rm -rf /var/lib/mysql/mysql

This leaves your other DB related files in place, only removing the mysql related files.

After running these:

sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean

Then reinstalling mysql:

sudo apt-get install mysql-server

It worked perfectly.

Get Android Device Name

I solved this by getting the Bluetooth name, but not from the BluetoothAdapter (that needs Bluetooth permission).

Here's the code:

Settings.Secure.getString(getContentResolver(), "bluetooth_name");

No extra permissions needed.

What exactly does an #if 0 ..... #endif block do?

It permanently comments out that code so the compiler will never compile it.

The coder can later change the #ifdef to have that code compile in the program if he wants to.

It's exactly like the code doesn't exist.

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

1) When the user logs out (Forms signout in Action) I want to redirect to a login page.

public ActionResult Logout() {
    //log out the user
    return RedirectToAction("Login");
}

2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)

Why would you want to redirect from a controller init?

the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:

public ActionResult Index() {
    return RedirectToAction("whateverAction", "whateverController");
}

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

You might check Select2 plugin:

http://ivaynberg.github.io/select2/

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.

It's quite popular and very maintainable. It should cover most of your needs if not all.

Is it possible to run an .exe or .bat file on 'onclick' in HTML

You can do it on Internet explorer with OCX component and on chrome browser using a chrome extension chrome document in any case need additional settings on the client system!

Important part of chrome extension source:

var port = chrome.runtime.connectNative("your.app.id"); 
      port.onMessage.addListener(onNativeMessage); 
      port.onDisconnect.addListener(onDisconnected);
      port.postMessage("send some data to STDIO");

permission file:

{
      "name": "your.app.id",
      "description": "Name of your extension",
      "path": "myapp.exe",
      "type": "stdio",
      "allowed_origins": [
            "chrome-extension://IDOFYOUREXTENSION_lokldaeplkmh/"
      ]
}

and windows registry settings:

HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\your.app.id
REG_EXPAND_SZ : c:\permissionsettings.json

what is difference between success and .done() method of $.ajax

In short, decoupling success callback function from the ajax function so later you can add your own handlers without modifying the original code (observer pattern).

Please find more detailed information from here: https://stackoverflow.com/a/14754681/1049184

JSON and XML comparison

Processing speed may not be the only relevant matter, however, as that's the question, here are some numbers in a benchmark: JSON vs. XML: Some hard numbers about verbosity. For the speed, in this simple benchmark, XML presents a 21% overhead over JSON.

An important note about the verbosity, which is as the article says, the most common complain: this is not so much relevant in practice (neither XML nor JSON data are typically handled by humans, but by machines), even if for the matter of speed, it requires some reasonable more time to compress.

Also, in this benchmark, a big amount of data was processed, and a typical web application won't transmit data chunks of such sizes, as big as 90MB, and compression may not be beneficial (for small enough data chunks, a compressed chunk will be bigger than the uncompressed chunk), so not applicable.

Still, if no compression is involved, JSON, as obviously terser, will weight less over the transmission channel, especially if transmitted through a WebSocket connection, where the absence of the classic HTTP overhead may make the difference at the advantage of JSON, even more significant.

After transmission, data is to be consumed, and this count in the overall processing time. If big or complex enough data are to be transmitted, the lack of a schema automatically checked for by a validating XML parser, may require more check on JSON data; these checks would have to be executed in JavaScript, which is not known to be particularly fast, and so it may present an additional overhead over XML in such cases.

Anyway, only testing will provides the answer for your particular use-case (if speed is really the only matter, and not standard nor safety nor integrity…).

Update 1: worth to mention, is EXI, the binary XML format, which offers compression at less cost than using Gzip, and save processing otherwise needed to decompress compressed XML. EXI is to XML, what BSON is to JSON. Have a quick overview here, with some reference to efficiency in both space and time: EXI: The last binary standard?.

Update 2: there also exists a binary XML performance reports, conducted by the W3C, as efficiency and low memory and CPU footprint, is also a matter for the XML area too: Efficient XML Interchange Evaluation.

Update 2015-03-01

Worth to be noticed in this context, as HTTP overhead was raised as an issue: the IANA has registered the EXI encoding (the efficient binary XML mentioned above), as a a Content Coding for the HTTP protocol (alongside with compress, deflate and gzip). This means EXI is an option which can be expected to be understood by browsers among possibly other HTTP clients. See Hypertext Transfer Protocol Parameters (iana.org).

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

You could use a Collector:

import java.util.*;
import java.util.stream.Collectors;

public class Defensive {

  public static void main(String[] args) {
    Map<String, Column> original = new HashMap<>();
    original.put("foo", new Column());
    original.put("bar", new Column());

    Map<String, Column> copy = original.entrySet()
        .stream()
        .collect(Collectors.toMap(Map.Entry::getKey,
                                  e -> new Column(e.getValue())));

    System.out.println(original);
    System.out.println(copy);
  }

  static class Column {
    public Column() {}
    public Column(Column c) {}
  }
}

Sort JavaScript object by key

Simple and readable snippet, using lodash.

You need to put the key in quotes only when calling sortBy. It doesn't have to be in quotes in the data itself.

_.sortBy(myObj, "key")

Also, your second parameter to map is wrong. It should be a function, but using pluck is easier.

_.map( _.sortBy(myObj, "key") , "value");

How to convert .pem into .key?

just as a .crt file is in .pem format, a .key file is also stored in .pem format. Assuming that the cert is the only thing in the .crt file (there may be root certs in there), you can just change the name to .pem. The same goes for a .key file. Which means of course that you can rename the .pem file to .key.

Which makes gtrig's answer the correct one. I just thought I'd explain why.

Multiple argument IF statement - T-SQL

That's the way to create complex boolean expressions: combine them with AND and OR. The snippet you posted doesn't throw any error for the IF.

Entity Framework Join 3 Tables

This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.

var fullEntries = dbContext.tbl_EntryPoint
    .Join(
        dbContext.tbl_Entry,
        entryPoint => entryPoint.EID,
        entry => entry.EID,
        (entryPoint, entry) => new { entryPoint, entry }
    )
    .Join(
        dbContext.tbl_Title,
        combinedEntry => combinedEntry.entry.TID,
        title => title.TID,
        (combinedEntry, title) => new 
        {
            UID = combinedEntry.entry.OwnerUID,
            TID = combinedEntry.entry.TID,
            EID = combinedEntry.entryPoint.EID,
            Title = title.Title
        }
    )
    .Where(fullEntry => fullEntry.UID == user.UID)
    .Take(10);

Grep characters before and after match?

You can use regexp grep for finding + second grep for highlight

echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}' | grep string

23_string_and

enter image description here

Open web in new tab Selenium + Python

This is a common code adapted from another examples:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.google.com/")

#open tab
# ... take the code from the options below

# Load a page 
driver.get('http://bings.com')
# Make the tests...

# close the tab
driver.quit()

the possible ways were:

  1. Sending <CTRL> + <T> to one element

    #open tab
    driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
    
  2. Sending <CTRL> + <T> via Action chains

    ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()
    
  3. Execute a javascript snippet

    driver.execute_script('''window.open("http://bings.com","_blank");''')
    

    In order to achieve this you need to ensure that the preferences browser.link.open_newwindow and browser.link.open_newwindow.restriction are properly set. The default values in the last versions are ok, otherwise you supposedly need:

    fp = webdriver.FirefoxProfile()
    fp.set_preference("browser.link.open_newwindow", 3)
    fp.set_preference("browser.link.open_newwindow.restriction", 2)
    
    driver = webdriver.Firefox(browser_profile=fp)
    

    the problem is that those preferences preset to other values and are frozen at least selenium 3.4.0. When you use the profile to set them with the java binding there comes an exception and with the python binding the new values are ignored.

    In Java there is a way to set those preferences without specifying a profile object when talking to geckodriver, but it seem to be not implemented yet in the python binding:

    FirefoxOptions options = new FirefoxOptions().setProfile(fp);
    options.addPreference("browser.link.open_newwindow", 3);
    options.addPreference("browser.link.open_newwindow.restriction", 2);
    FirefoxDriver driver = new FirefoxDriver(options);
    

The third option did stop working for python in selenium 3.4.0.

The first two options also did seem to stop working in selenium 3.4.0. They do depend on sending CTRL key event to an element. At first glance it seem that is a problem of the CTRL key, but it is failing because of the new multiprocess feature of Firefox. It might be that this new architecture impose new ways of doing that, or maybe is a temporary implementation problem. Anyway we can disable it via:

fp = webdriver.FirefoxProfile()
fp.set_preference("browser.tabs.remote.autostart", False)
fp.set_preference("browser.tabs.remote.autostart.1", False)
fp.set_preference("browser.tabs.remote.autostart.2", False)

driver = webdriver.Firefox(browser_profile=fp)

... and then you can use successfully the first way.

Make REST API call in Swift

Swift 5 & 4

let params = ["username":"john", "password":"123456"] as Dictionary<String, String>

var request = URLRequest(url: URL(string: "http://localhost:8080/api/1/login")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
    print(response!)
    do {
        let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
        print(json)
    } catch {
        print("error")
    }
})

task.resume()

Node.js Best Practice Exception Handling

Update: Joyent now has their own guide. The following information is more of a summary:

Safely "throwing" errors

Ideally we'd like to avoid uncaught errors as much as possible, as such, instead of literally throwing the error, we can instead safely "throw" the error using one of the following methods depending on our code architecture:

  • For synchronous code, if an error happens, return the error:

    // Define divider as a syncrhonous function
    var divideSync = function(x,y) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by returning it
            return new Error("Can't divide by zero")
        }
        else {
            // no error occured, continue on
            return x/y
        }
    }
    
    // Divide 4/2
    var result = divideSync(4,2)
    // did an error occur?
    if ( result instanceof Error ) {
        // handle the error safely
        console.log('4/2=err', result)
    }
    else {
        // no error occured, continue on
        console.log('4/2='+result)
    }
    
    // Divide 4/0
    result = divideSync(4,0)
    // did an error occur?
    if ( result instanceof Error ) {
        // handle the error safely
        console.log('4/0=err', result)
    }
    else {
        // no error occured, continue on
        console.log('4/0='+result)
    }
    
  • For callback-based (ie. asynchronous) code, the first argument of the callback is err, if an error happens err is the error, if an error doesn't happen then err is null. Any other arguments follow the err argument:

    var divide = function(x,y,next) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by calling the completion callback
            // with the first argument being the error
            next(new Error("Can't divide by zero"))
        }
        else {
            // no error occured, continue on
            next(null, x/y)
        }
    }
    
    divide(4,2,function(err,result){
        // did an error occur?
        if ( err ) {
            // handle the error safely
            console.log('4/2=err', err)
        }
        else {
            // no error occured, continue on
            console.log('4/2='+result)
        }
    })
    
    divide(4,0,function(err,result){
        // did an error occur?
        if ( err ) {
            // handle the error safely
            console.log('4/0=err', err)
        }
        else {
            // no error occured, continue on
            console.log('4/0='+result)
        }
    })
    
  • For eventful code, where the error may happen anywhere, instead of throwing the error, fire the error event instead:

    // Definite our Divider Event Emitter
    var events = require('events')
    var Divider = function(){
        events.EventEmitter.call(this)
    }
    require('util').inherits(Divider, events.EventEmitter)
    
    // Add the divide function
    Divider.prototype.divide = function(x,y){
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by emitting it
            var err = new Error("Can't divide by zero")
            this.emit('error', err)
        }
        else {
            // no error occured, continue on
            this.emit('divided', x, y, x/y)
        }
    
        // Chain
        return this;
    }
    
    // Create our divider and listen for errors
    var divider = new Divider()
    divider.on('error', function(err){
        // handle the error safely
        console.log(err)
    })
    divider.on('divided', function(x,y,result){
        console.log(x+'/'+y+'='+result)
    })
    
    // Divide
    divider.divide(4,2).divide(4,0)
    

Safely "catching" errors

Sometimes though, there may still be code that throws an error somewhere which can lead to an uncaught exception and a potential crash of our application if we don't catch it safely. Depending on our code architecture we can use one of the following methods to catch it:

  • When we know where the error is occurring, we can wrap that section in a node.js domain

    var d = require('domain').create()
    d.on('error', function(err){
        // handle the error safely
        console.log(err)
    })
    
    // catch the uncaught errors in this asynchronous or synchronous code block
    d.run(function(){
        // the asynchronous or synchronous code that we want to catch thrown errors on
        var err = new Error('example')
        throw err
    })
    
  • If we know where the error is occurring is synchronous code, and for whatever reason can't use domains (perhaps old version of node), we can use the try catch statement:

    // catch the uncaught errors in this synchronous code block
    // try catch statements only work on synchronous code
    try {
        // the synchronous code that we want to catch thrown errors on
        var err = new Error('example')
        throw err
    } catch (err) {
        // handle the error safely
        console.log(err)
    }
    

    However, be careful not to use try...catch in asynchronous code, as an asynchronously thrown error will not be caught:

    try {
        setTimeout(function(){
            var err = new Error('example')
            throw err
        }, 1000)
    }
    catch (err) {
        // Example error won't be caught here... crashing our app
        // hence the need for domains
    }
    

    If you do want to work with try..catch in conjunction with asynchronous code, when running Node 7.4 or higher you can use async/await natively to write your asynchronous functions.

    Another thing to be careful about with try...catch is the risk of wrapping your completion callback inside the try statement like so:

    var divide = function(x,y,next) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by calling the completion callback
            // with the first argument being the error
            next(new Error("Can't divide by zero"))
        }
        else {
            // no error occured, continue on
            next(null, x/y)
        }
    }
    
    var continueElsewhere = function(err, result){
            throw new Error('elsewhere has failed')
    }
    
    try {
            divide(4, 2, continueElsewhere)
            // ^ the execution of divide, and the execution of 
            //   continueElsewhere will be inside the try statement
    }
    catch (err) {
            console.log(err.stack)
            // ^ will output the "unexpected" result of: elsewhere has failed
    }
    

    This gotcha is very easy to do as your code becomes more complex. As such, it is best to either use domains or to return errors to avoid (1) uncaught exceptions in asynchronous code (2) the try catch catching execution that you don't want it to. In languages that allow for proper threading instead of JavaScript's asynchronous event-machine style, this is less of an issue.

  • Finally, in the case where an uncaught error happens in a place that wasn't wrapped in a domain or a try catch statement, we can make our application not crash by using the uncaughtException listener (however doing so can put the application in an unknown state):

    // catch the uncaught errors that weren't wrapped in a domain or try catch statement
    // do not use this in modules, but only in applications, as otherwise we could have multiple of these bound
    process.on('uncaughtException', function(err) {
        // handle the error safely
        console.log(err)
    })
    
    // the asynchronous or synchronous code that emits the otherwise uncaught error
    var err = new Error('example')
    throw err
    

How can I do division with variables in a Linux shell?

Those variables are shell variables. To expand them as parameters to another program (ie expr), you need to use the $ prefix:

expr $x / $y

The reason it complained is because it thought you were trying to operate on alphabetic characters (ie non-integer)

If you are using the Bash shell, you can achieve the same result using expression syntax:

echo $((x / y))

Or:

z=$((x / y))
echo $z

What is the alternative for ~ (user's home directory) on Windows command prompt?

You can do almost the same yourself. Open Environment Variables and click "New" Button in the "User Variables for ..." .
Variable Name: ~
Variable Value: Click "Browse Directory..." button and choose a directory which you want.

And after this, open cmd and type this:
cd %~%
. It works.

Classes residing in App_Code is not accessible

I found it easier to move the files into a separate Class Library project and then reference that project in the web project and apply the namespace in the using section of the file. For some reason the other solutions were not working for me, but this work around did.

Rails: select unique values from a column

Some answers don't take into account the OP wants a array of values

Other answers don't work well if your Model has thousands of records

That said, I think a good answer is:

    Model.uniq.select(:ratings).map(&:ratings)
    => "SELECT DISTINCT ratings FROM `models` " 

Because, first you generate a array of Model (with diminished size because of the select), then you extract the only attribute those selected models have (ratings)

Remove ListView items in Android

It's simple .First you should clear your collection and after clear list like this code :

 yourCollection.clear();
 setListAdapter(null);

How to display data from database into textbox, and update it

Populate the text box values in the Page Init event as opposed to using the Postback.

protected void Page_Init(object sender, EventArgs e)
{
    DropDownTitle();
}

How to add a "sleep" or "wait" to my Lua Script?

if you're using a MacBook or UNIX based system, use this:

function wait(time)
if tonumber(time) ~= nil then
os.execute("Sleep "..tonumber(time))
else
os.execute("Sleep "..tonumber("0.1"))
end
wait()

Session TimeOut in web.xml

If you don't want a timeout happening for some purpose:

<session-config>
    <session-timeout>0</session-timeout>
</session-config>

Should result in no timeout at all -> infinite

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

Select box arrow style

http://jsfiddle.net/u3cybk2q/2/ check on windows, iOS and Android (iexplorer patch)

_x000D_
_x000D_
.styled-select select {_x000D_
   background: transparent;_x000D_
   width: 240px;_x000D_
   padding: 5px;_x000D_
   font-size: 16px;_x000D_
   line-height: 1;_x000D_
   border: 0;_x000D_
   border-radius: 0;_x000D_
   height: 34px;_x000D_
   -webkit-appearance: none;_x000D_
}_x000D_
.styled-select {_x000D_
   width: 240px;_x000D_
   height: 34px;_x000D_
   overflow: visible;_x000D_
   background: url(http://nightly.enyojs.com/latest/lib/moonstone/dist/moonstone/images/caret-black-small-down-icon.png) no-repeat right #FFF;_x000D_
   border: 1px solid #ccc;_x000D_
}_x000D_
.styled-select select::-ms-expand {_x000D_
    display: none;_x000D_
}
_x000D_
<div class="styled-select">_x000D_
   <select>_x000D_
      <option>Here is the first option</option>_x000D_
      <option>The second option</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I check if an array includes a value in JavaScript?

Solution that works in all modern browsers:

function contains(arr, obj) {
  const stringifiedObj = JSON.stringify(obj); // Cache our object to not call `JSON.stringify` on every iteration
  return arr.some(item => JSON.stringify(item) === stringifiedObj);
}

Usage:

contains([{a: 1}, {a: 2}], {a: 1}); // true

IE6+ solution:

function contains(arr, obj) {
  var stringifiedObj = JSON.stringify(obj)
  return arr.some(function (item) {
    return JSON.stringify(item) === stringifiedObj;
  });
}

// .some polyfill, not needed for IE9+
if (!('some' in Array.prototype)) {
  Array.prototype.some = function (tester, that /*opt*/) {
    for (var i = 0, n = this.length; i < n; i++) {
      if (i in this && tester.call(that, this[i], i, this)) return true;
    } return false;
  };
}

Usage:

contains([{a: 1}, {a: 2}], {a: 1}); // true

Why to use JSON.stringify?

Array.indexOf and Array.includes (as well as most of the answers here) only compare by reference and not by value.

[{a: 1}, {a: 2}].includes({a: 1});
// false, because {a: 1} is a new object

Bonus

Non-optimized ES6 one-liner:

[{a: 1}, {a: 2}].some(item => JSON.stringify(item) === JSON.stringify({a: 1));
// true

Note: Comparing objects by value will work better if the keys are in the same order, so to be safe you might sort the keys first with a package like this one: https://www.npmjs.com/package/sort-keys


Updated the contains function with a perf optimization. Thanks itinance for pointing it out.

How to implement a material design circular progress bar in android

The platform uses a vector drawable, so you can't reuse it as in in older versions.
However, the support lib v4 contains a backport of this drawable : http://androidxref.com/5.1.0_r1/xref/frameworks/support/v4/java/android/support/v4/widget/MaterialProgressDrawable.java It has a @hide annotation (it is here for the SwipeRefreshLayout), but nothing prevents you from copying this class in your codebase.

Accessing Objects in JSON Array (JavaScript)

You can loop the array with a for loop and the object properties with for-in loops.

for (var i=0; i<result.length; i++)
    for (var name in result[i]) {
        console.log("Item name: "+name);
        console.log("Source: "+result[i][name].sourceUuid);
        console.log("Target: "+result[i][name].targetUuid);
    }

AngularJs ReferenceError: $http is not defined

Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.


You can also use $inject to add a dependency:

var MyController = function($scope, $http) {
  // ...
}
MyController.$inject = ['$scope', '$http'];

How to scale down a range of numbers with a known min and max value

Here's some JavaScript for copy-paste ease (this is irritate's answer):

function scaleBetween(unscaledNum, minAllowed, maxAllowed, min, max) {
  return (maxAllowed - minAllowed) * (unscaledNum - min) / (max - min) + minAllowed;
}

Applied like so, scaling the range 10-50 to a range between 0-100.

var unscaledNums = [10, 13, 25, 28, 43, 50];

var maxRange = Math.max.apply(Math, unscaledNums);
var minRange = Math.min.apply(Math, unscaledNums);

for (var i = 0; i < unscaledNums.length; i++) {
  var unscaled = unscaledNums[i];
  var scaled = scaleBetween(unscaled, 0, 100, minRange, maxRange);
  console.log(scaled.toFixed(2));
}

0.00, 18.37, 48.98, 55.10, 85.71, 100.00

Edit:

I know I answered this a long time ago, but here's a cleaner function that I use now:

Array.prototype.scaleBetween = function(scaledMin, scaledMax) {
  var max = Math.max.apply(Math, this);
  var min = Math.min.apply(Math, this);
  return this.map(num => (scaledMax-scaledMin)*(num-min)/(max-min)+scaledMin);
}

Applied like so:

[-4, 0, 5, 6, 9].scaleBetween(0, 100);

[0, 30.76923076923077, 69.23076923076923, 76.92307692307692, 100]

Get the POST request body from HttpServletRequest

This works for both GET and POST:

@Context
private HttpServletRequest httpRequest;


private void printRequest(HttpServletRequest httpRequest) {
    System.out.println(" \n\n Headers");

    Enumeration headerNames = httpRequest.getHeaderNames();
    while(headerNames.hasMoreElements()) {
        String headerName = (String)headerNames.nextElement();
        System.out.println(headerName + " = " + httpRequest.getHeader(headerName));
    }

    System.out.println("\n\nParameters");

    Enumeration params = httpRequest.getParameterNames();
    while(params.hasMoreElements()){
        String paramName = (String)params.nextElement();
        System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
    }

    System.out.println("\n\n Row data");
    System.out.println(extractPostRequestBody(httpRequest));
}

static String extractPostRequestBody(HttpServletRequest request) {
    if ("POST".equalsIgnoreCase(request.getMethod())) {
        Scanner s = null;
        try {
            s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s.hasNext() ? s.next() : "";
    }
    return "";
}

Setting Authorization Header of HttpClient

BaseWebApi.cs

public abstract class BaseWebApi
{
    //Inject HttpClient from Ninject
    private readonly HttpClient _httpClient;
    public BaseWebApi(HttpClient httpclient)
    {
        _httpClient = httpClient;
    }

    public async Task<TOut> PostAsync<TOut>(string method, object param, Dictionary<string, string> headers, HttpMethod httpMethod)
    {
        //Set url

        HttpResponseMessage response;
        using (var request = new HttpRequestMessage(httpMethod, url))
        {
            AddBody(param, request);
            AddHeaders(request, headers);
            response = await _httpClient.SendAsync(request, cancellationToken);
        }

        if(response.IsSuccessStatusCode)
        {
             return await response.Content.ReadAsAsync<TOut>();
        }
        //Exception handling
    }

    private void AddHeaders(HttpRequestMessage request, Dictionary<string, string> headers)
    {
        request.Headers.Accept.Clear();
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        if (headers == null) return;

        foreach (var header in headers)
        {
            request.Headers.Add(header.Key, header.Value);
        }
    }

    private static void AddBody(object param, HttpRequestMessage request)
    {
        if (param != null)
        {
            var content = JsonConvert.SerializeObject(param);
            request.Content = new StringContent(content);
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        }
    }

SubWebApi.cs

public sealed class SubWebApi : BaseWebApi
{
    public SubWebApi(HttpClient httpClient) : base(httpClient) {}

    public async Task<StuffResponse> GetStuffAsync(int cvr)
    {
        var method = "get/stuff";
        var request = new StuffRequest 
        {
            query = "GiveMeStuff"
        }
        return await PostAsync<StuffResponse>(method, request, GetHeaders(), HttpMethod.Post);
    }
    private Dictionary<string, string> GetHeaders()
    {
        var headers = new Dictionary<string, string>();
        var basicAuth = GetBasicAuth();
        headers.Add("Authorization", basicAuth);
        return headers;
    }

    private string GetBasicAuth()
    {
        var byteArray = Encoding.ASCII.GetBytes($"{SystemSettings.Username}:{SystemSettings.Password}");
        var authString = Convert.ToBase64String(byteArray);
        return $"Basic {authString}";
    }
}

Send Email to multiple Recipients with MailMessage?

I've tested this using the following powershell script and using (,) between the addresses. It worked for me!

$EmailFrom = "<[email protected]>";
$EmailPassword = "<password>";
$EmailTo = "<[email protected]>,<[email protected]>";
$SMTPServer = "<smtp.server.com>";
$SMTPPort = <port>;
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer,$SMTPPort);
$SMTPClient.EnableSsl = $true;
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $EmailPassword);
$Subject = "Notification from XYZ";
$Body = "this is a notification from XYZ Notifications..";
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body);

How to start an application using android ADB tools?

It's possible to run application specifying package name only using monkey tool by follow this pattern:

adb shell monkey -p your.app.package.name -c android.intent.category.LAUNCHER 1

Command is used to run app using monkey tool which generates random input for application. The last part of command is integer which specify the number of generated random input for app. In this case the number is 1, which in fact is used to launch the app (icon click).

PHP "php://input" vs $_POST

php://input can give you the raw bytes of the data. This is useful if the POSTed data is a JSON encoded structure, which is often the case for an AJAX POST request.

Here's a function to do just that:

  /**
   * Returns the JSON encoded POST data, if any, as an object.
   * 
   * @return Object|null
   */
  private function retrieveJsonPostData()
  {
    // get the raw POST data
    $rawData = file_get_contents("php://input");

    // this returns null if not valid json
    return json_decode($rawData);
  }

The $_POST array is more useful when you're handling key-value data from a form, submitted by a traditional POST. This only works if the POSTed data is in a recognised format, usually application/x-www-form-urlencoded (see http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 for details).

Get first 100 characters from string, respecting full words

If you define words as "sequences of characters delimited by space"... Use strrpos() to find the last space in the string, shorten to that position, trim the result.

Can I add extension methods to an existing static class?

The following was rejected as an edit to tvanfosson's answer. I was asked to contribute it as my own answer. I used his suggestion and finished the implementation of a ConfigurationManager wrapper. In principle I simply filled out the ... in tvanfosson's answer.

No. Extension methods require an instance of an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.

public static class ConfigurationManagerWrapper
{
    public static NameValueCollection AppSettings
    {
        get { return ConfigurationManager.AppSettings; }
    }

    public static ConnectionStringSettingsCollection ConnectionStrings
    {
        get { return ConfigurationManager.ConnectionStrings; }
    }

    public static object GetSection(string sectionName)
    {
        return ConfigurationManager.GetSection(sectionName);
    }

    public static Configuration OpenExeConfiguration(string exePath)
    {
        return ConfigurationManager.OpenExeConfiguration(exePath);
    }

    public static Configuration OpenMachineConfiguration()
    {
        return ConfigurationManager.OpenMachineConfiguration();
    }

    public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel)
    {
        return ConfigurationManager.OpenMappedExeConfiguration(fileMap, userLevel);
    }

    public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap)
    {
        return ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
    }

    public static void RefreshSection(string sectionName)
    {
        ConfigurationManager.RefreshSection(sectionName);
    }
}

Get MIME type from filename extension

would be better if someone can use similar features as in libmagic on linux, as that is what I guess a better way to detect types of files than relaying on the extension name of a file.

For example, if I rename a file from mypicture.jpg to mypicture.txt On linux, it will still be reported as a picture But using this methodology here, it will be reported as text file.

Regards Tomas

Found shared references to a collection org.hibernate.HibernateException

Posting here because it's taken me over 2 weeks to get to the bottom of this, and I still haven't fully resolved it.

There is a chance, that you're also just running into this bug which has been around since 2017 and hasn't been addressed.

I honestly have no clue how to get around this bug. I'm posting here for my sanity and hopefully to shave a couple weeks of your googling. I'd love any input anyone may have, but my particular "answer" to this problem was not listed in any of the above answers.

Combine two (or more) PDF's

Following method merges two pdfs( f1 and f2) using iTextSharp. The second pdf is appended after a specific index of f1.

 string f1 = "D:\\a.pdf";
 string f2 = "D:\\Iso.pdf";
 string outfile = "D:\\c.pdf";
 appendPagesFromPdf(f1, f2, outfile, 3);




  public static void appendPagesFromPdf(String f1,string f2, String destinationFile, int startingindex)
        {
            PdfReader p1 = new PdfReader(f1);
            PdfReader p2 = new PdfReader(f2);
            int l1 = p1.NumberOfPages, l2 = p2.NumberOfPages;


            //Create our destination file
            using (FileStream fs = new FileStream(destinationFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                Document doc = new Document();

                PdfWriter w = PdfWriter.GetInstance(doc, fs);
                doc.Open();
                for (int page = 1; page <= startingindex; page++)
                {
                    doc.NewPage();
                    w.DirectContent.AddTemplate(w.GetImportedPage(p1, page), 0, 0);
                    //Used to pull individual pages from our source

                }//  copied pages from first pdf till startingIndex
                for (int i = 1; i <= l2;i++)
                {
                    doc.NewPage();
                    w.DirectContent.AddTemplate(w.GetImportedPage(p2, i), 0, 0);
                }// merges second pdf after startingIndex
                for (int i = startingindex+1; i <= l1;i++)
                {
                    doc.NewPage();
                    w.DirectContent.AddTemplate(w.GetImportedPage(p1, i), 0, 0);
                }// continuing from where we left in pdf1 

                doc.Close();
                p1.Close();
                p2.Close();

            }
        }

python .replace() regex

No. Regular expressions in Python are handled by the re module.

article = re.sub(r'(?is)</html>.+', '</html>', article)

In general:

text_after = re.sub(regex_search_term, regex_replacement, text_before)

Github: Can I see the number of downloads for a repo?

To check the number of times a release file/package was downloaded you can go to https://githubstats0.firebaseapp.com

It gives you a total download count and a break up of of total downloads per release tag.

Highlight the difference between two strings in PHP

I would recommend looking at these awesome functions from PHP core:

similar_text — Calculate the similarity between two strings

http://www.php.net/manual/en/function.similar-text.php

levenshtein — Calculate Levenshtein distance between two strings

http://www.php.net/manual/en/function.levenshtein.php

soundex — Calculate the soundex key of a string

http://www.php.net/manual/en/function.soundex.php

metaphone — Calculate the metaphone key of a string

http://www.php.net/manual/en/function.metaphone.php

From inside of a Docker container, how do I connect to the localhost of the machine?

Simplest solution for Mac OSX

Just use the IP address of your Mac. On the Mac run this to get the IP address and use it from within the container:

$ ifconfig | grep 'inet 192'| awk '{ print $2}'

As long as the server running locally on your Mac or in another docker container is listening to 0.0.0.0, the docker container will be able to reach out at that address.

If you just want to access another docker container that is listening on 0.0.0.0 you can use 172.17.0.1

Escape invalid XML characters in C#

string XMLWriteStringWithoutIllegalCharacters(string UnfilteredString)
{
    if (UnfilteredString == null)
        return string.Empty;

    return XmlConvert.EncodeName(UnfilteredString);
}

string XMLReadStringWithoutIllegalCharacters(string FilteredString)
{
    if (UnfilteredString == null)
        return string.Empty;

    return XmlConvert.DecodeName(UnfilteredString);
}

This simple method replace the invalid characters with the same value but accepted in the XML context.


To write string use XMLWriteStringWithoutIllegalCharacters(string UnfilteredString).
To read string use XMLReadStringWithoutIllegalCharacters(string FilteredString).

How to terminate process from Python using pid?

So, not directly related but this is the first question that appears when you try to find how to terminate a process running from a specific folder using Python.

It also answers the question in a way(even though it is an old one with lots of answers).

While creating a faster way to scrape some government sites for data I had an issue where if any of the processes in the pool got stuck they would be skipped but still take up memory from my computer. This is the solution I reached for killing them, if anyone knows a better way to do it please let me know!

import pandas as pd
import wmi
from re import escape
import os

def kill_process(kill_path, execs):
    f = wmi.WMI()
    esc = escape(kill_path)
    temp = {'id':[], 'path':[], 'name':[]}
    for process in f.Win32_Process():
        temp['id'].append(process.ProcessId)
        temp['path'].append(process.ExecutablePath)
        temp['name'].append(process.Name)
    temp = pd.DataFrame(temp)
    temp = temp.dropna(subset=['path']).reset_index().drop(columns=['index'])
    temp = temp.loc[temp['path'].str.contains(esc)].loc[temp.name.isin(execs)].reset_index().drop(columns=['index'])
    [os.system('taskkill /PID {} /f'.format(t)) for t in temp['id']]

AngularJS does not send hidden field value

You can always use a type=text and display:none; since Angular ignores hidden elements. As OP says, normally you wouldn't do this, but this seems like a special case.

<input type="text" name="someData" ng-model="data" style="display: none;"/>

Java replace all square brackets in a string

The replaceAll method is attempting to match the String literal [] which does not exist within the String try replacing these items separately.

String str = "[Chrissman-@1]";
str = str.replaceAll("\\[", "").replaceAll("\\]","");

Compile error: package javax.servlet does not exist

JSP and Servlet are Server side Programming. As it comes as an built in package inside a Server like Tomcat. The path may be like wise

C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\jsp-api.jar
C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar

Just you want to Do is Add this in the following way

Right Click> My Computer>Advanced>Environment Variables>System variables

Do> New..> Variable name:CLASSPATH
           Variable value:CLASSPATH=.;C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar;

Why use a ReentrantLock if one can use synchronized(this)?

You can use reentrant locks with a fairness policy or timeout to avoid thread starvation. You can apply a thread fairness policy. it will help avoid a thread waiting forever to get to your resources.

private final ReentrantLock lock = new ReentrantLock(true);
//the param true turns on the fairness policy. 

The "fairness policy" picks the next runnable thread to execute. It is based on priority, time since last run, blah blah

also, Synchronize can block indefinitely if it cant escape the block. Reentrantlock can have timeout set.

Show div #id on click with jQuery

You can use jQuery toggle to show and hide the div. The script will be like this

  <script type="text/javascript">
    jQuery(function(){
      jQuery("#music").click(function () {
        jQuery("#musicinfo").toggle("slow");
      });
    });
</script>

Is there a MySQL option/feature to track history of changes to records?

Why not simply use bin log files? If the replication is set on the Mysql server, and binlog file format is set to ROW, then all the changes could be captured.

A good python library called noplay can be used. More info here.

Using R to download zipped data file, extract, and import data

For Mac (and I assume Linux)...

If the zip archive contains a single file, you can use the bash command funzip, in conjuction with fread from the data.table package:

library(data.table)
dt <- fread("curl http://www.newcl.org/data/zipfiles/a1.zip | funzip")

In cases where the archive contains multiple files, you can use tar instead to extract a specific file to stdout:

dt <- fread("curl http://www.newcl.org/data/zipfiles/a1.zip | tar -xf- --to-stdout *a1.dat")

MySQL load NULL values from CSV data

(variable1, @variable2, ..) SET variable2 = nullif(@variable2, '' or ' ') >> you can put any condition

Setting href attribute at runtime

To get or set an attribute of an HTML element, you can use the element.attr() function in jQuery.

To get the href attribute, use the following code:

var a_href = $('selector').attr('href');

To set the href attribute, use the following code:

$('selector').attr('href','http://example.com');

In both cases, please use the appropriate selector. If you have set the class for the anchor element, use '.class-name' and if you have set the id for the anchor element, use '#element-id'.

How to get the IP address of the docker host from inside a docker container

TLDR for Mac and Windows

docker run -it --rm alpine nslookup host.docker.internal

... prints the host's IP address ...

nslookup: can't resolve '(null)': Name does not resolve

Name:      host.docker.internal
Address 1: 192.168.65.2

Details

On Mac and Windows, you can use the special DNS name host.docker.internal.

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.

jQuery plugin returning "Cannot read property of undefined"

The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:

var len = menuitems.length;
for (var i = 0; i < len; i++){
    (function(i) {
      $('<li/>',{
          'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
          'click':function(){
              menuitems[i].action();
          },
          'class':o.itemClass
      }).appendTo('.'+o.listClass);
    })(i);
}

In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.

Retrieving the last record in each group - MySQL

UPD: 2017-03-31, the version 5.7.5 of MySQL made the ONLY_FULL_GROUP_BY switch enabled by default (hence, non-deterministic GROUP BY queries became disabled). Moreover, they updated the GROUP BY implementation and the solution might not work as expected anymore even with the disabled switch. One needs to check.

Bill Karwin's solution above works fine when item count within groups is rather small, but the performance of the query becomes bad when the groups are rather large, since the solution requires about n*n/2 + n/2 of only IS NULL comparisons.

I made my tests on a InnoDB table of 18684446 rows with 1182 groups. The table contains testresults for functional tests and has the (test_id, request_id) as the primary key. Thus, test_id is a group and I was searching for the last request_id for each test_id.

Bill's solution has already been running for several hours on my dell e4310 and I do not know when it is going to finish even though it operates on a coverage index (hence using index in EXPLAIN).

I have a couple of other solutions that are based on the same ideas:

  • if the underlying index is BTREE index (which is usually the case), the largest (group_id, item_value) pair is the last value within each group_id, that is the first for each group_id if we walk through the index in descending order;
  • if we read the values which are covered by an index, the values are read in the order of the index;
  • each index implicitly contains primary key columns appended to that (that is the primary key is in the coverage index). In solutions below I operate directly on the primary key, in you case, you will just need to add primary key columns in the result.
  • in many cases it is much cheaper to collect the required row ids in the required order in a subquery and join the result of the subquery on the id. Since for each row in the subquery result MySQL will need a single fetch based on primary key, the subquery will be put first in the join and the rows will be output in the order of the ids in the subquery (if we omit explicit ORDER BY for the join)

3 ways MySQL uses indexes is a great article to understand some details.

Solution 1

This one is incredibly fast, it takes about 0,8 secs on my 18M+ rows:

SELECT test_id, MAX(request_id) AS request_id
FROM testresults
GROUP BY test_id DESC;

If you want to change the order to ASC, put it in a subquery, return the ids only and use that as the subquery to join to the rest of the columns:

SELECT test_id, request_id
FROM (
    SELECT test_id, MAX(request_id) AS request_id
    FROM testresults
    GROUP BY test_id DESC) as ids
ORDER BY test_id;

This one takes about 1,2 secs on my data.

Solution 2

Here is another solution that takes about 19 seconds for my table:

SELECT test_id, request_id
FROM testresults, (SELECT @group:=NULL) as init
WHERE IF(IFNULL(@group, -1)=@group:=test_id, 0, 1)
ORDER BY test_id DESC, request_id DESC

It returns tests in descending order as well. It is much slower since it does a full index scan but it is here to give you an idea how to output N max rows for each group.

The disadvantage of the query is that its result cannot be cached by the query cache.

How do you create a REST client for Java?

As I mentioned in this thread I tend to use Jersey which implements JAX-RS and comes with a nice REST client. The nice thing is if you implement your RESTful resources using JAX-RS then the Jersey client can reuse the entity providers such as for JAXB/XML/JSON/Atom and so forth - so you can reuse the same objects on the server side as you use on the client side unit test.

For example here is a unit test case from the Apache Camel project which looks up XML payloads from a RESTful resource (using the JAXB object Endpoints). The resource(uri) method is defined in this base class which just uses the Jersey client API.

e.g.

    clientConfig = new DefaultClientConfig();
    client = Client.create(clientConfig);

    resource = client.resource("http://localhost:8080");
    // lets get the XML as a String
    String text = resource("foo").accept("application/xml").get(String.class);        

BTW I hope that future version of JAX-RS add a nice client side API along the lines of the one in Jersey

How do I get countifs to select all non-blank cells in Excel?

You can try this :

=COUNTIF(Data!A2:A300,"<>"&"")

Converting a UNIX Timestamp to Formatted Date String

You can do like as.....

$originalDate = "1585876500";

echo $newDate = date("Y-m-d h:i:sa", date($originalDate));

Should have subtitle controller already set Mediaplayer error Android

Also you can only set mediaPlayer.reset() and in onDestroy set it to release.

Join String list elements with a delimiter in one step

You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+");

"commence before first target. Stop." error

This could also caused by mismatching brace/parenthesis.

$(TARGET}:
    do_something

Just use parenthesises and you'll be fine.

Python - Create list with numbers between 2 values?

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

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

Output:

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

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

AWS Lambda import module error in python

I found this hard way after trying all of the solutions above. If you're using sub-directories in the zip file, ensure you include the __init__.py file in each of the sub-directories and that worked for me.

Webview load html from assets directory

You are getting the WebView before setting the Content view so the wv is probably null.

public class ViewWeb extends Activity {  
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);
            setContentView(R.layout.webview);  
            WebView wv;  
            wv = (WebView) findViewById(R.id.webView1);  
            wv.loadUrl("file:///android_asset/aboutcertified.html");   // now it will not fail here
        }  
    }

Accessing SQL Database in Excel-VBA

Is that a proper connection string?
Where is the SQL Server instance located?

You will need to verify that you are able to conenct to SQL Server using the connection string, you specified above.

EDIT: Look at the State property of the recordset to see if it is Open?
Also, change the CursorLocation property to adUseClient before opening the recordset.

read subprocess stdout line by line

Bit late to the party, but was surprised not to see what I think is the simplest solution here:

import io
import subprocess

proc = subprocess.Popen(["prog", "arg"], stdout=subprocess.PIPE)
for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"):  # or another encoding
    # do something with line

(This requires Python 3.)

How to clear memory to prevent "out of memory error" in excel vba?

If you operate on a large dataset, it is very possible that arrays will be used. For me creating a few arrays from 500 000 rows and 30 columns worksheet caused this error. I solved it simply by using the line below to get rid of array which is no longer necessary to me, before creating another one:

Erase vArray

Also if only 2 columns out of 30 are used, it is a good idea to create two 1-column arrays instead of one with 30 columns. It doesn't affect speed, but there will be a difference in memory usage.

No newline after div?

div.noWrap {
    display: inline;
    }

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

Convert InputStream to BufferedReader

BufferedReader can't wrap an InputStream directly. It wraps another Reader. In this case you'd want to do something like:

BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

Javascript/Jquery to change class onclick?

With jquery you could do to sth. like this, which will simply switch classes.

$('.showhide').click(function() {
    $(this).removeClass('myclass');
    $(this).addClass('showhidenew');
});

If you want to switch classes back and forth on each click, you can use toggleClass, like so:

$('.showhide').click(function() {
    $(this).toggleClass('myclass');
    $(this).toggleClass('showhidenew');
});

How do I rotate the Android emulator display?

Make sure that "Auto Rotate" on your Android settings is enabled

Press F9 two times in less than 2 seconds = Normal view 0/360º

Press F10 two times in less than 2 seconds = Rotate 180º.

Press F11 two times in less than 2 seconds = Rotate 90º to the RiGHT.

Press F12 two times in less than 2 seconds = Rotate 90º to the LEFT.

Making a div vertically scrollable using CSS

You can use this code instead.

<div id="" style="overflow-y:scroll; overflow-x:hidden; height:400px;">


overflow-x: The overflow-x property specifies what to do with the left/right edges of the content - if it overflows the element's content area.
overflow-y: The overflow-y property specifies what to do with the top/bottom edges of the content - if it overflows the element's content area.

Values
visible: Default value. The content is not clipped, and it may be rendered outside the content box.
hidden: The content is clipped - and no scrolling mechanism is provided.
scroll: The content is clipped and a scrolling mechanism is provided.
auto: Should cause a scrolling mechanism to be provided for overflowing boxes.
initial: Sets this property to its default value.
inherit Inherits this property from its parent element.

DateTime.Now.ToShortDateString(); replace month and day

Use DateTime.ToString with the specified format MM.dd.yyyy:

this.TextBox3.Text = DateTime.Now.ToString("MM.dd.yyyy");

Here, MM means the month from 01 to 12, dd means the day from 01 to 31 and yyyy means the year as a four-digit number.

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

You might have to do something like

var content= (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d

then you should be able to use

result = $(content).find("#result")