Programs & Examples On #Uinavigationbar

The UINavigationBar class implements a control for navigating hierarchical content in iOS. It’s a bar, typically displayed at the top of the screen, containing buttons for navigating up and down a hierarchy. The primary properties are a left (back) button, a center title, and an optional right button. You can specify custom views for each of these. The most common way to use a navigation bar is in conjunction with a UINavigationController object

Navigation bar show/hide

If you want to detect the status of navigation bar wether it is hidden/shown. You can simply use following code to detect -

if self.navigationController?.isNavigationBarHidden{
    print("Show navigation bar")
} else {
    print("hide navigation bar")
}

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

We're all working around some old bugs that haven't been fixed likely because it's "by design." I ran into the freezing problem @iwasrobbed described elsewhere when trying to nil the interactivePopGestureRecognizer's delegate which seemed like it should've worked. If you want swipe behavior reconsider using backBarButtonItem which you can customize.

I also ran into interactivePopGestureRecognizer not working when the UINavigationBar is hidden. If hiding the navigation bar is a concern for you, reconsider your design before implementing a workaround for a bug.

How to hide UINavigationBar 1px bottom line

Two lines solution that works for me. Try to add this in ViewDidLoad method:

navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
self.extendedLayoutIncludesOpaqueBars = true

Navigation bar with UIImage for title

I tried @Jack's answer above, the logo did appear however the image occupied the whole Navigation Bar. I wanted it to fit.

Swift 4, Xcode 9.2

1.Assign value to navigation controller, UIImage. Adjust size by dividing frame and Image size.

func addNavBarImage() {

        let navController = navigationController!

        let image = UIImage(named: "logo-signIn6.png") //Your logo url here
        let imageView = UIImageView(image: image)

        let bannerWidth = navController.navigationBar.frame.size.width
        let bannerHeight = navController.navigationBar.frame.size.height

        let bannerX = bannerWidth / 2 - (image?.size.width)! / 2
        let bannerY = bannerHeight / 2 - (image?.size.height)! / 2

        imageView.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
        imageView.contentMode = .scaleAspectFit

        navigationItem.titleView = imageView
    }
  1. Add the function right under viewDidLoad()

        addNavBarImage() 
    

Note on the image asset. Before uploading, I adjusted the logo with extra margins rather than cropped at the edges.

Final result:

enter image description here

transparent navigation bar ios

Try this, it works for me if you also need to support ios7, it is based on the transparency of UItoolBar:

[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
                                                  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.view.backgroundColor = [UIColor clearColor];
    UIToolbar* blurredView = [[UIToolbar alloc] initWithFrame:self.navigationController.navigationBar.bounds];
    [blurredView setBarStyle:UIBarStyleBlack];
    [blurredView setBarTintColor:[UIColor redColor]];
    [self.navigationController.navigationBar insertSubview:blurredView atIndex:0];

NavigationBar bar, tint, and title text color in iOS 8

Swift 4.1

Add a func to viewDidLoad

override func viewDidLoad() {
  super.viewDidLoad()

  setup()
}   

In the setup() function add:

func setup() {

        navigationController?.navigationBar.prefersLargeTitles = true
        navigationController?.navigationBar.barStyle = .blackOpaque
        navigationItem.title = "YOUR_TITLE_HERE"
        navigationController?.navigationBar.barTintColor = .black
        let attributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
        navigationController?.navigationBar.largeTitleTextAttributes = attributes
    }

Add a UIView above all, even the navigation bar

Note if you want add view in Full screen then only use below code

Add these extension of UIViewController

public extension UIViewController {
   internal func makeViewAsFullScreen() {
      var viewFrame:CGRect = self.view.frame
      if viewFrame.origin.y > 0 || viewFrame.origin.x > 0 {
        self.view.frame = UIScreen.main.bounds
      }
   }
}

Continue as normal adding process of subview

Now use in adding UIViewController's viewDidAppear

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

     self.makeViewAsFullScreen()
}

presenting ViewController with NavigationViewController swift

My navigation bar was not showing, so I have used the following method in Swift 2 iOS 9

let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as! Dashboard

// Creating a navigation controller with viewController at the root of the navigation stack.
let navController = UINavigationController(rootViewController: viewController)
self.presentViewController(navController, animated:true, completion: nil)

Make UINavigationBar transparent

extension UINavigationBar {
var isTransperent: Bool {
        get {
            return false // Just to satisfy property
        }
        set {
            if newValue == true {
                self.shadowImage   = UIImage()
                self.isTranslucent = true
                self.setBackgroundImage(UIImage(), for: .default)
            }else{
                self.shadowImage   = UIImage()
                self.isTranslucent = false
                self.setBackgroundImage(nil, for: .default)
            }
        }
    }
}

Trying to handle "back" navigation button action in iOS

None of the other solutions worked for me, but this does:

Create your own subclass of UINavigationController, make it implement the UINavigationBarDelegate (no need to manually set the navigation bar's delegate), add a UIViewController extension that defines a method to be called on a back button press, and then implement this method in your UINavigationController subclass:

func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
    self.topViewController?.methodToBeCalledOnBackButtonPress()
    self.popViewController(animated: true)
    return true
}

How to add a button to UINavigationBar?

Sample code to set the rightbutton on a NavigationBar.

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
    style:UIBarButtonItemStyleDone target:nil action:nil];
UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"Title"];
item.rightBarButtonItem = rightButton;
item.hidesBackButton = YES;
[bar pushNavigationItem:item animated:NO];

But normally you would have a NavigationController, enabling you to write:

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
    style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightButton;

How to change UINavigationBar background color from the AppDelegate

In Swift 4.2 and Xcode 10.1

You can change your navigation bar colour from your AppDelegate directly to your entire project.

In didFinishLaunchingWithOptions launchOptions: write below to lines of code

UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)

Here

tintColor is for to set background images like back button & menu lines images etc. (See below left and right menu image)

barTintColor is for navigation bar background colour

If you want to set specific view controller navigation bar colour, write below code in viewDidLoad()

//Add navigation bar colour
navigationController?.navigationBar.barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)
navigationController?.navigationBar.tintColor = UIColor.white

enter image description here

Changing navigation bar color in Swift

Swift 4:

Perfectly working code to change the navigation bar appearance at application level.

enter image description here

// MARK: Navigation Bar Customisation

// To change background colour.
UINavigationBar.appearance().barTintColor = .init(red: 23.0/255, green: 197.0/255, blue: 157.0/255, alpha: 1.0)

// To change colour of tappable items.
UINavigationBar.appearance().tintColor = .white

// To apply textAttributes to title i.e. colour, font etc.
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor : UIColor.white,
                                                    .font : UIFont.init(name: "AvenirNext-DemiBold", size: 22.0)!]
// To control navigation bar's translucency.
UINavigationBar.appearance().isTranslucent = false

Happy Coding!

How to change Navigation Bar color in iOS 7?

self.navigationBar.barTintColor = [UIColor blueColor];
self.navigationBar.tintColor = [UIColor whiteColor];
self.navigationBar.translucent = NO;

// *barTintColor* sets the background color
// *tintColor* sets the buttons color

IOS 7 Navigation Bar text and arrow color

[[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];

iPhone: Setting Navigation Bar Title

If you want to change the title of a navBar inside a tabBar controller, do this:

-(void)viewDidAppear:(BOOL)animated {
    self.navigationController.navigationBar.topItem.title = @"myTitle";
}

How to hide a navigation bar from first ViewController in Swift?

You can do it from the window controller (Swift3)

class WindowController: NSWindowController {

    override func windowDidLoad() {
        super.windowDidLoad()

        window?.titleVisibility = .hidden
    }
}

Change color of Back button in navigation bar

Swift 5.3:

UINavigationBar.appearance().backIndicatorImage = UIImage(named: "custom-back-image")
UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "custom-back-image")

Programmatically get height of navigation bar

If you want to get the navigationBar height only, it's simple:

extension UIViewController{
   var navigationBarHeight: CGFloat {
       return self.navigationController?.navigationBar.frame.height ?? 0.0
   }
}

However, if you need the height of top notch of iPhone you don't need to get the navigationBar height and add to it the statusBar height, you can simply call safeAreaInsets that's why exist.

self.view.safeAreaInsets.top

Swift programmatically navigate to another view controller/scene

You should push the new viewcontroller by using current navigation controller, not present.

self.navigationController.pushViewController(nextViewController, animated: true)

How do I change the title of the "back" button on a Navigation Bar

iOS 11+ solution - Doesn't require to create backbutton again.

Set backButtonTitle as a space on the previous screen.

// If navigation is from A -> B, set in A's `viewDidLoad`.
navigationItem.backButtonTitle = " "

UINavigationBar custom back button without title

Set back button item title as empty String.

[self.navigationController.navigationBar.backItem setTitle:@""];

Add button to navigationbar programmatically

If you are not looking for a BarButtonItem but simple button on navigationBar then below code works:

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setBackgroundImage:[UIImage imageNamed:@"NavBar.png"] forState:UIControlStateNormal];
[aButton addTarget:self
            action:@selector(showButtonView:)
  forControlEvents:UIControlEventTouchUpInside];
aButton.frame = CGRectMake(260.0, 10.0, 30.0, 30.0);
[self.navigationController.navigationBar addSubview:aButton];

iPhone Navigation Bar Title text color

The solution by tewha works well if you are trying to change the color on a page, but I want to be able to change the color on every page. I made some small modifications so that it would work for all pages on a UINavigationController

NavigationDelegate.h

//This will change the color of the navigation bar
#import <Foundation/Foundation.h>
@interface NavigationDelegate : NSObject<UINavigationControllerDelegate> {
}
@end

NavigationDelegate.m

#import "NavigationDelegate.h"
@implementation NavigationDelegate

- (void)navigationController:(UINavigationController *)navigationController 
      willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    CGRect frame = CGRectMake(0, 0, 200, 44);//TODO: Can we get the size of the text?
    UILabel* label = [[[UILabel alloc] initWithFrame:frame] autorelease];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:20.0];
    label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor yellowColor];
    //The two lines below are the only ones that have changed
    label.text=viewController.title;
    viewController.navigationItem.titleView = label;
}
@end

Changing navigation title programmatically

Swift 5.1

// Set NavigationBar Title Programmatically and Dynamic

Note : First add NavigationControllerItem to Your ViewController then goto their ViewController.swift file and Just Copy and Paste this in viewDidLoad().

navigationItem.title = "Your Title Here"

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

The Three20 library has a way to do this:

  UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle: @"Title" style:UIBarButtonItemStylePlain 
                                                                target:self action:@selector(foo)];

  UIColor* darkBlue = RGBCOLOR(109, 132, 162);

  TTShapeStyle* style = [TTShapeStyle styleWithShape:[TTRoundedLeftArrowShape shapeWithRadius:4.5] next:
    [TTShadowStyle styleWithColor:RGBCOLOR(255,255,255) blur:1 offset:CGSizeMake(0, 1) next:
    [TTReflectiveFillStyle styleWithColor:darkBlue next:
    [TTBevelBorderStyle styleWithHighlight:[darkBlue shadow]
                                     shadow:[darkBlue multiplyHue:1 saturation:0.5 value:0.5]
                                      width:1 lightSource:270 next:
    [TTInsetStyle styleWithInset:UIEdgeInsetsMake(0, -1, 0, -1) next:
    [TTBevelBorderStyle styleWithHighlight:nil shadow:RGBACOLOR(0,0,0,0.15)
                                        width:1 lightSource:270 next:nil]]]]]];

  TTView* view = [[[TTView alloc] initWithFrame:CGRectMake(0, 0, 80, 35)] autorelease];
  view.backgroundColor = [UIColor clearColor];
  view.style = style;
  backButton.customView = view;


  self.navigationItem.leftBarButtonItem = backButton;

How to add a right button to a UINavigationController?

Try this.It work for me.

Navigation bar and also added background image to right button.

 UIBarButtonItem *Savebtn=[[UIBarButtonItem alloc]initWithImage:[[UIImage    
 imageNamed:@"bt_save.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] 
 style:UIBarButtonItemStylePlain target:self action:@selector(SaveButtonClicked)];
 self.navigationItem.rightBarButtonItem=Savebtn;

Removing the title text of an iOS UIBarButtonItem

I am listing out the solutions which worked for me so far.

override func viewDidLoad() {
super.viewDidLoad()   



self.navigationController?.navigationBar.topItem?.title = "" // 1

 let barAppearace = UIBarButtonItem.appearance()
barAppearace.setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics:UIBarMetrics.Default)  // 2

UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Normal) //3

UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Highlighted) //4   



}

Java - How to find the redirected url of a url?

Simply call getUrl() on URLConnection instance after calling getInputStream():

URLConnection con = new URL( url ).openConnection();
System.out.println( "orignal url: " + con.getURL() );
con.connect();
System.out.println( "connected url: " + con.getURL() );
InputStream is = con.getInputStream();
System.out.println( "redirected url: " + con.getURL() );
is.close();

If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:

HttpURLConnection con = (HttpURLConnection)(new URL( url ).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
int responseCode = con.getResponseCode();
System.out.println( responseCode );
String location = con.getHeaderField( "Location" );
System.out.println( location );

How to append in a json file in Python?

json_obj=json.dumps(a_dict, ensure_ascii=False)

How do I configure the proxy settings so that Eclipse can download new plugins?

I installed HandyCache, in them install link on my general proxy.

In IE set proxy 127.0.0.1.

In Eclipse, Window > Preferences > General > Network Connections, set Active Provider = Native.

Format date in a specific timezone

A couple of answers already mention that moment-timezone is the way to go with named timezone. I just want to clarify something about this library that was pretty confusing to me. There is a difference between these two statements:

moment.tz(date, format, timezone)

moment(date, format).tz(timezone)

Assuming that a timezone is not specified in the date passed in:

The first code takes in the date and assumes the timezone is the one passed in. The second one will take date, assume the timezone from the browser and then change the time and timezone according to the timezone passed in.

Example:

moment.tz('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss', 'UTC').format() // "2018-07-17T19:00:00Z"

moment('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss').tz('UTC').format() // "2018-07-18T00:00:00Z"

My timezone is +5 from utc. So in the first case it does not change and it sets the date and time to have utc timezone.

In the second case, it assumes the date passed in is in -5, then turns it into UTC, and that's why it spits out the date "2018-07-18T00:00:00Z"

NOTE: The format parameter is really important. If omitted moment might fall back to the Date class which can unpredictable behaviors


Assuming the timezone is specified in the date passed in:

In this case they both behave equally


Even though now I understand why it works that way, I thought this was a pretty confusing feature and worth explaining.

Update Eclipse with Android development tools v. 23

I faced the same problem and solved it. You need to uninstall the Android plugin entirely from within Eclipse (from the "about" section..), including trace view..

Then added the ADT Plugin again (https://dl-ssl.google.com/android/eclipse/) and install it.

The problem is solved!

I guess it's a bug with the SDK manager or ADT Plugin update mechanism...

https with WCF error: "Could not find base address that matches scheme https"

I think you are trying to configure your service in a similar way to the following config. There is more information here: Specify a Service with Two Endpoints Using Different Binding Values. Also, other than for development, it's probably not a good idea to have both HTTP & HTTPS endpoints to the same service. It kinda defeats the purpose of HTTPS. Hope this helps!

<service type="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null">
    <endpoint
        address="http://computer:8080/Hello"
        contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
        binding="basicHttpBinding"
        bindingConfiguration="shortTimeout"
    </endpoint>
    <endpoint
        address="http://computer:8080/Hello"
        contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
        binding="basicHttpBinding"
        bindingConfiguration="Secure"
     </endpoint>
</service>
<bindings>
    <basicHttpBinding 
        name="shortTimeout"
        timeout="00:00:00:01" 
     />
     <basicHttpBinding 
        name="Secure">
        <Security mode="Transport" />
     </basicHttpBinding>
</bindings>

Traverse all the Nodes of a JSON Object Tree with JavaScript

Depends on what you want to do. Here's an example of traversing a JavaScript object tree, printing keys and values as it goes:

function js_traverse(o) {
    var type = typeof o 
    if (type == "object") {
        for (var key in o) {
            print("key: ", key)
            js_traverse(o[key])
        }
    } else {
        print(o)
    }
}

js> foobar = {foo: "bar", baz: "quux", zot: [1, 2, 3, {some: "hash"}]}
[object Object]
js> js_traverse(foobar)                 
key:  foo
bar
key:  baz
quux
key:  zot
key:  0
1
key:  1
2
key:  2
3
key:  3
key:  some
hash

HTML table with 100% width, with vertical scroll inside tbody

In modern browsers, you can simply use css:

th {
  position: sticky;
  top: 0;
  z-index: 2;
}

Convert array of indices to 1-hot encoded numpy array

Here's a dimensionality-independent standalone solution.

This will convert any N-dimensional array arr of nonnegative integers to a one-hot N+1-dimensional array one_hot, where one_hot[i_1,...,i_N,c] = 1 means arr[i_1,...,i_N] = c. You can recover the input via np.argmax(one_hot, -1)

def expand_integer_grid(arr, n_classes):
    """

    :param arr: N dim array of size i_1, ..., i_N
    :param n_classes: C
    :returns: one-hot N+1 dim array of size i_1, ..., i_N, C
    :rtype: ndarray

    """
    one_hot = np.zeros(arr.shape + (n_classes,))
    axes_ranges = [range(arr.shape[i]) for i in range(arr.ndim)]
    flat_grids = [_.ravel() for _ in np.meshgrid(*axes_ranges, indexing='ij')]
    one_hot[flat_grids + [arr.ravel()]] = 1
    assert((one_hot.sum(-1) == 1).all())
    assert(np.allclose(np.argmax(one_hot, -1), arr))
    return one_hot

Detect Close windows event by jQuery

There is no specific event for capturing browser close event. But we can detect by the browser positions XY.

<script type="text/javascript">
$(document).ready(function() {
  $(document).mousemove(function(e) {
    if(e.pageY <= 5)
    {
        //this condition would occur when the user brings their cursor on address bar 
        //do something here 
    }
  });
});
</script>

How to draw a line in android

You can draw multiple straight lines on view using Finger paint example which is in Developer android. example link

Just comment: mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2); You will be able to draw straight lines.

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class JoinPointsActivity extends Activity  {
    /** Called when the activity is first created. */
    Paint mPaint;
    float Mx1,My1;
    float x,y;
    @Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.main);
        MyView view1 =new MyView(this);
        view1.setBackgroundResource(R.drawable.image_0031_layer_1);
        setContentView(view1);


        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(0xFFFF0000);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
       // mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(10);

    }

    public class MyView extends View {

        private static final float MINP = 0.25f;
        private static final float MAXP = 0.75f;

      private Bitmap  mBitmap;
        private Canvas  mCanvas;
        private Path    mPath;
       private Paint   mBitmapPaint;

        public MyView(Context c) {
            super(c);

            mPath = new Path();
          mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        }

        @Override
       protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            mCanvas = new Canvas(mBitmap);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(0xFFAAAAAA);
           // canvas.drawLine(mX, mY, Mx1, My1, mPaint);
           // canvas.drawLine(mX, mY, x, y, mPaint);
            canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
            canvas.drawPath(mPath, mPaint);

        }

        private float mX, mY;
        private static final float TOUCH_TOLERANCE = 4;

        private void touch_start(float x, float y) {
            mPath.reset();
            mPath.moveTo(x, y);
            mX = x;
            mY = y;
        }
        private void touch_move(float x, float y) {
            float dx = Math.abs(x - mX);
            float dy = Math.abs(y - mY);
            if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
               // mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
                mX = x;
                mY = y;
            }
        }
        private void touch_up() {
            mPath.lineTo(mX, mY);
            // commit the path to our offscreen
            mCanvas.drawPath(mPath, mPaint);
            // kill this so we don't double draw
            mPath.reset();
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float x = event.getX();
            float y = event.getY();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    touch_start(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_MOVE:
                    touch_move(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    touch_up();
               //   Mx1=(int) event.getX();
                 //  My1= (int) event.getY();
                   invalidate();
                    break;
            }
            return true;
        }
    }

}

How to find SQL Server running port?

Try to enable the protocol by: Configuration Manger > SQL server Network Configuration > Protocols for MSSQLSERVER > properties of TCP/IP

Assign output to variable in Bash

Same with something more complex...getting the ec2 instance region from within the instance.

INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")

echo $INSTANCE_REGION

How to retrieve the last autoincremented ID from a SQLite table?

One other option is to look at the system table sqlite_sequence. Your sqlite database will have that table automatically if you created any table with autoincrement primary key. This table is for sqlite to keep track of the autoincrement field so that it won't repeat the primary key even after you delete some rows or after some insert failed (read more about this here http://www.sqlite.org/autoinc.html).

So with this table there is the added benefit that you can find out your newly inserted item's primary key even after you inserted something else (in other tables, of course!). After making sure that your insert is successful (otherwise you will get a false number), you simply need to do:

select seq from sqlite_sequence where name="table_name"

stop all instances of node.js server

you can try

killall node

you can also try

killall nodejs

How to do multiple conditions for single If statement

Use the 'And' keyword for a logical and. Like this:

If Not ((filename = testFileName) And (fileName <> "")) Then

JavaScript calculate the day of the year (1 - 366)

It always get's me worried when mixing maths with date functions (it's so easy to miss some leap year other detail). Say you have:

var d = new Date();

I would suggest using the following, days will be saved in day:

for(var day = d.getDate(); d.getMonth(); day += d.getDate())
    d.setDate(0);

Can't see any reason why this wouldn't work just fine (and I wouldn't be so worried about the few iterations since this will not be used so intensively).

What should I do if the current ASP.NET session is null?

In my case ASP.NET State Service was stopped. Changing the Startup type to Automatic and starting the service manually for the first time solved the issue.

What is the difference between a data flow diagram and a flow chart?

Data Flow and Flow Chart differ in processes, flow, and timing.

  1. Processes

    a.) On DFDs, processes can operate in parallel (at-the-same-time).

    b.) On flowcharts, processes execute one at a time.


  1. Flow

    a.) DFDs show the flow of data through a system

    b.) Flowcharts show the flow of control (sequence and transfer of control)


  1. Timing

    a.) Processes on a DFD can have dramatically different timing (daily, weekly, on demand)

    b.) Processes on flowcharts are part of a single program with consistent timing

How to trigger click event on href element

The native DOM method does the right thing:

$('.cssbuttongo')[0].click();
                  ^
              Important!

This works regardless of whether the href is a URL, a fragment (e.g. #blah) or even a javascript:.

Note that this calls the DOM click method instead of the jQuery click method (which is very incomplete and completely ignores href).

How to know what the 'errno' means?

Type sudo apt-get install moreutils into your shell and then, once that has installed, type errno 2. You can also use errno -l for all error numbers, or see only the file ones by piping it to grep, like this: errno -l | grep file.

How do I pass JavaScript variables to PHP?

I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.

It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.

One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:

<img src="pic.php">

The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.

How to start Apache and MySQL automatically when Windows 8 comes up

Copy xampp_start.exe from your XAMPP install directory to C:\Users\YOUR USERNAME\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup.

Replace YOUR USERNAME with your username.

SQL Server - after insert trigger - update another column in the same table

Yea...having an additional step to update a table in which you can set the value in the inital insert is probably an extra, avoidable process. Do you have access to the original insert statement where you can actually just insert the part_description into the part_description_upper column using UPPER(part_description) value?

After thinking, you probably don't have access as you would have probably done that so should also give some options as well...

1) Depends on the need for this part_description_upper column, if just for "viewing" then can just use the returned part_description value and "ToUpper()" it (depending on programming language).

2) If want to avoid "realtime" processing, can just create a sql job to go through your values once a day during low traffic periods and update that column to the UPPER part_description value for any that are currently not set.

3) go with your trigger (and watch for recursion as others have mentioned)...

HTH

Dave

How to display Woocommerce product price by ID number on a custom page?

If you have the product's ID you can use that to create a product object:

$_product = wc_get_product( $product_id );

Then from the object you can run any of WooCommerce's product methods.

$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();

Update
Please review the Codex article on how to write your own shortcode.

Integrating the WooCommerce product data might look something like this:

function so_30165014_price_shortcode_callback( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'bartag' );

    $html = '';

    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
         $_product = wc_get_product( $atts['id'] );
         $html = "price = " . $_product->get_price();
    }
    return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );

Your shortcode would then look like [woocommerce_price id="99"]

Python how to plot graph sine wave

import matplotlib.pyplot as plt # For ploting
import numpy as np # to work with numerical data efficiently

fs = 100 # sample rate 
f = 2 # the frequency of the signal

x = np.arange(fs) # the points on the x axis for plotting
# compute the value (amplitude) of the sin wave at the for each sample
y = np.sin(2*np.pi*f * (x/fs)) 

#this instruction can only be used with IPython Notbook. 
% matplotlib inline
# showing the exact location of the smaples
plt.stem(x,y, 'r', )
plt.plot(x,y)

enter image description here

Correct use for angular-translate in controllers

To make a translation in the controller you could use $translate service:

$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
    vm.si = translations['COMMON.SI'];
    vm.no = translations['COMMON.NO'];
});

That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope event: $translateChangeSuccess and do the same translation there:

    $rootScope.$on('$translateChangeSuccess', function () {
        $translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
            vm.si = translations['COMMON.SI'];
            vm.no = translations['COMMON.NO'];
        });
    });

Of course, you could encapsulate the $translateservice in a method and call it in the controller and in the $translateChangeSucesslistener.

Display current date and time without punctuation

Without punctuation (as @Burusothman has mentioned):

current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;

O/P:

20170115072120

With punctuation:

current_date_time="`date "+%Y-%m-%d %H:%M:%S"`";
echo $current_date_time;

O/P:

2017-01-15 07:25:33

How to open a folder in Windows Explorer from VBA?

Here is some more cool knowledge to go with this:

I had a situation where I needed to be able to find folders based on a bit of criteria in the record and then open the folder(s) that were found. While doing work on finding a solution I created a small database that asks for a search starting folder gives a place for 4 pieces of criteria and then allows the user to do criteria matching that opens the 4 (or more) possible folders that match the entered criteria.

Here is the whole code on the form:

Option Compare Database
Option Explicit

Private Sub cmdChooseFolder_Click()

    Dim inputFileDialog As FileDialog
    Dim folderChosenPath As Variant

    If MsgBox("Clear List?", vbYesNo, "Clear List") = vbYes Then DoCmd.RunSQL "DELETE * FROM tblFileList"
    Me.sfrmFolderList.Requery

    Set inputFileDialog = Application.FileDialog(msoFileDialogFolderPicker)

    With inputFileDialog
        .Title = "Select Folder to Start with"
        .AllowMultiSelect = False
        If .Show = False Then Exit Sub
        folderChosenPath = .SelectedItems(1)
    End With

    Me.txtStartPath = folderChosenPath

    Call subListFolders(Me.txtStartPath, 1)

End Sub
Private Sub cmdFindFolderPiece_Click()

    Dim strCriteria As String
    Dim varCriteria As Variant
    Dim varIndex As Variant
    Dim intIndex As Integer

    varCriteria = Array(Nz(Me.txtSerial, "Null"), Nz(Me.txtCustomerOrder, "Null"), Nz(Me.txtAXProject, "Null"), Nz(Me.txtWorkOrder, "Null"))
    intIndex = 0

    For Each varIndex In varCriteria
        strCriteria = varCriteria(intIndex)
        If strCriteria <> "Null" Then
            Call fnFindFoldersWithCriteria(TrailingSlash(Me.txtStartPath), strCriteria, 1)
        End If
        intIndex = intIndex + 1
    Next varIndex

    Set varIndex = Nothing
    Set varCriteria = Nothing
    strCriteria = ""

End Sub
Private Function fnFindFoldersWithCriteria(ByVal strStartPath As String, ByVal strCriteria As String, intCounter As Integer)

    Dim fso As New FileSystemObject
    Dim fldrStartFolder As Folder
    Dim subfldrInStart As Folder
    Dim subfldrInSubFolder As Folder
    Dim subfldrInSubSubFolder As String
    Dim strActionLog As String

    Set fldrStartFolder = fso.GetFolder(strStartPath)

'    Debug.Print "Criteria: " & Replace(strCriteria, " ", "", 1, , vbTextCompare) & " and Folder Name is " & Replace(fldrStartFolder.Name, " ", "", 1, , vbTextCompare) & " and Path is: " & fldrStartFolder.Path

    If fnCompareCriteriaWithFolderName(fldrStartFolder.Name, strCriteria) Then
'        Debug.Print "Found and Opening: " & fldrStartFolder.Name & "Because of: " & strCriteria
        Shell "EXPLORER.EXE" & " " & Chr(34) & fldrStartFolder.Path & Chr(34), vbNormalFocus
    Else
        For Each subfldrInStart In fldrStartFolder.SubFolders

            intCounter = intCounter + 1

            Debug.Print "Criteria: " & Replace(strCriteria, " ", "", 1, , vbTextCompare) & " and Folder Name is " & Replace(subfldrInStart.Name, " ", "", 1, , vbTextCompare) & " and Path is: " & fldrStartFolder.Path

            If fnCompareCriteriaWithFolderName(subfldrInStart.Name, strCriteria) Then
'                Debug.Print "Found and Opening: " & subfldrInStart.Name & "Because of: " & strCriteria
                Shell "EXPLORER.EXE" & " " & Chr(34) & subfldrInStart.Path & Chr(34), vbNormalFocus
            Else
                Call fnFindFoldersWithCriteria(subfldrInStart, strCriteria, intCounter)
            End If
            Me.txtProcessed = intCounter
            Me.txtProcessed.Requery
        Next
    End If

    Set fldrStartFolder = Nothing
    Set subfldrInStart = Nothing
    Set subfldrInSubFolder = Nothing
    Set fso = Nothing

End Function
Private Function fnCompareCriteriaWithFolderName(strFolderName As String, strCriteria As String) As Boolean

    fnCompareCriteriaWithFolderName = False

    fnCompareCriteriaWithFolderName = InStr(1, Replace(strFolderName, " ", "", 1, , vbTextCompare), Replace(strCriteria, " ", "", 1, , vbTextCompare), vbTextCompare) > 0

End Function

Private Sub subListFolders(ByVal strFolders As String, intCounter As Integer)
    Dim dbs As Database
    Dim fso As New FileSystemObject
    Dim fldFolders As Folder
    Dim fldr As Folder
    Dim subfldr As Folder
    Dim sfldFolders As String
    Dim strSQL As String

    Set fldFolders = fso.GetFolder(TrailingSlash(strFolders))
    Set dbs = CurrentDb

    strSQL = "INSERT INTO tblFileList (FilePath, FileName, FolderSize) VALUES (" & Chr(34) & fldFolders.Path & Chr(34) & ", " & Chr(34) & fldFolders.Name & Chr(34) & ", '" & fldFolders.Size & "')"
    dbs.Execute strSQL

    For Each fldr In fldFolders.SubFolders
        intCounter = intCounter + 1
        strSQL = "INSERT INTO tblFileList (FilePath, FileName, FolderSize) VALUES (" & Chr(34) & fldr.Path & Chr(34) & ", " & Chr(34) & fldr.Name & Chr(34) & ", '" & fldr.Size & "')"
        dbs.Execute strSQL
        For Each subfldr In fldr.SubFolders
            intCounter = intCounter + 1
            sfldFolders = subfldr.Path
            Call subListFolders(sfldFolders, intCounter)
            Me.sfrmFolderList.Requery
        Next
        Me.txtListed = intCounter
        Me.txtListed.Requery
    Next

    Set fldFolders = Nothing
    Set fldr = Nothing
    Set subfldr = Nothing
    Set dbs = Nothing

End Sub

Private Function TrailingSlash(varIn As Variant) As String
    If Len(varIn) > 0& Then
        If Right(varIn, 1&) = "\" Then
            TrailingSlash = varIn
        Else
            TrailingSlash = varIn & "\"
        End If
    End If
End Function

The form has a subform based on the table, the form has 4 text boxes for the criteria, 2 buttons leading to the click procedures and 1 other text box to store the string for the start folder. There are 2 text boxes that are used to show the number of folders listed and the number processed when searching them for the criteria.

If I had the Rep I would post a picture... :/

I have some other things I wanted to add to this code but haven't had the chance yet. I want to have a way to store the ones that worked in another table or get the user to mark them as good to store.

I can not claim full credit for all the code, I cobbled some of it together from stuff I found all around, even in other posts on stackoverflow.

I really like the idea of posting questions here and then answering them yourself because as the linked article says, it makes it easy to find the answer for later reference.

When I finish the other parts I want to add I will post the code for that too. :)

How to replace comma with a dot in the number (or any replacement)

Per the docs, replace returns the new string - it does not modify the string you pass it.

var tt="88,9827";
tt = tt.replace(/,/g, '.');
^^^^
alert(tt);

Set the maximum character length of a UITextField in Swift

Swift 4, simply use:

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return range.location < 10
}

What EXACTLY is meant by "de-referencing a NULL pointer"?

A NULL pointer points to memory that doesn't exist, and will raise Segmentation fault. There's an easier way to de-reference a NULL pointer, take a look.

int main(int argc, char const *argv[])
{
    *(int *)0 = 0; // Segmentation fault (core dumped)
    return 0;
}

Since 0 is never a valid pointer value, a fault occurs.

SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=NULL}

How to use boost bind with a member function

Use the following instead:

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

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

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

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

First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:

global $db;

And I guess, when you wrote:

if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:

if ($result->num_rows==1) { return true; } else { return false; }

Fastest way to compute entropy in Python

from collections import Counter
from scipy import stats

labels = [0.9, 0.09, 0.1]
stats.entropy(list(Counter(labels).keys()), base=2)

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

I had the same "reflection exception" error. The solution was to copy the class file to the server, from dev, for me. dumb mistake, but given how many files we deal with its easy to forget to copy them over to the server every time.

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

Pass data to layout that are common to all pages

Presumably, the primary use case for this is to get a base model to the view for all (or the majority of) controller actions.

Given that, I've used a combination of several of these answers, primary piggy backing on Colin Bacon's answer.

It is correct that this is still controller logic because we are populating a viewmodel to return to a view. Thus the correct place to put this is in the controller.

We want this to happen on all controllers because we use this for the layout page. I am using it for partial views that are rendered in the layout page.

We also still want the added benefit of a strongly typed ViewModel

Thus, I have created a BaseViewModel and BaseController. All ViewModels Controllers will inherit from BaseViewModel and BaseController respectively.

The code:

BaseController

public class BaseController : Controller
{
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);

        var model = filterContext.Controller.ViewData.Model as BaseViewModel;

        model.AwesomeModelProperty = "Awesome Property Value";
        model.FooterModel = this.getFooterModel();
    }

    protected FooterModel getFooterModel()
    {
        FooterModel model = new FooterModel();
        model.FooterModelProperty = "OMG Becky!!! Another Awesome Property!";
    }
}

Note the use of OnActionExecuted as taken from this SO post

HomeController

public class HomeController : BaseController
{
    public ActionResult Index(string id)
    {
        HomeIndexModel model = new HomeIndexModel();

        // populate HomeIndexModel ...

        return View(model);
    }
}

BaseViewModel

public class BaseViewModel
{
    public string AwesomeModelProperty { get; set; }
    public FooterModel FooterModel { get; set; }
}

HomeViewModel

public class HomeIndexModel : BaseViewModel
{

    public string FirstName { get; set; }

    // other awesome properties
}

FooterModel

public class FooterModel
{
    public string FooterModelProperty { get; set; }
}

Layout.cshtml

@model WebSite.Models.BaseViewModel
<!DOCTYPE html>
<html>
<head>
    < ... meta tags and styles and whatnot ... >
</head>
<body>
    <header>
        @{ Html.RenderPartial("_Nav", Model.FooterModel.FooterModelProperty);}
    </header>

    <main>
        <div class="container">
            @RenderBody()
        </div>

        @{ Html.RenderPartial("_AnotherPartial", Model); }
        @{ Html.RenderPartial("_Contact"); }
    </main>

    <footer>
        @{ Html.RenderPartial("_Footer", Model.FooterModel); }
    </footer>

    < ... render scripts ... >

    @RenderSection("scripts", required: false)
</body>
</html>

_Nav.cshtml

@model string
<nav>
    <ul>
        <li>
            <a href="@Model" target="_blank">Mind Blown!</a>
        </li>
    </ul>
</nav>

Hopefully this helps.

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.

e.g. This will give the error because @SQL needs to be NVARCHAR

DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

So:

DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

How to hide a mobile browser's address bar?

You can go to fullscreen when user allows it :)

<button id="goFS">Go fullscreen</button>
<script>
  var goFS = document.getElementById("goFS");
  goFS.addEventListener("click", function() {
      
   const elem = document.documentElement;
   if (elem.requestFullscreen) {elem.requestFullscreen()}
   
  }, false);
</script>

How to flush route table in windows?

route -f causes damage. So we need to either disconnect the correct parts of the routing table or find out how to rebuild it.

What is a deadlock?

Mutex in essence is a lock, providing protected access to shared resources. Under Linux, the thread mutex data type is pthread_mutex_t. Before use, initialize it.

To access to shared resources, you have to lock on the mutex. If the mutex already on the lock, the call will block the thread until the mutex is unlocked. Upon completion of the visit to shared resources, you have to unlock them.

Overall, there are a few unwritten basic principles:

  • Obtain the lock before using the shared resources.

  • Holding the lock as short time as possible.

  • Release the lock if the thread returns an error.

refresh div with jquery

I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this

_x000D_
_x000D_
$("#panel").toggle().toggle();
_x000D_
_x000D_
_x000D_

it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.

Android Webview - Webpage should fit the device screen

webview.setInitialScale(1);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setJavaScriptEnabled(true);

will work, but remember to remove something like:

<meta name="viewport" content="user-scalable=no"/>

if existed in the html file or change user-scalable=yes, otherwise it won't.

Return a value if no rows are found in Microsoft tSQL

No record matched means no record returned. There's no place for the "value" of 0 to go if no records are found. You could create a crazy UNION query to do what you want but much, much, much better simply to check the number of records in the result set.

Trying to get property of non-object - Laravel 5

I had also this problem. Add code like below in the related controller (e.g. UserController)

$users = User::all();
return view('mytemplate.home.homeContent')->with('users',$users);

Proper way to handle multiple forms on one page in Django

I needed multiple forms that are independently validated on the same page. The key concepts I was missing were 1) using the form prefix for the submit button name and 2) an unbounded form does not trigger validation. If it helps anyone else, here is my simplified example of two forms AForm and BForm using TemplateView based on the answers by @adam-nelson and @daniel-sokolowski and comment by @zeraien (https://stackoverflow.com/a/17303480/2680349):

# views.py
def _get_form(request, formcls, prefix):
    data = request.POST if prefix in request.POST else None
    return formcls(data, prefix=prefix)

class MyView(TemplateView):
    template_name = 'mytemplate.html'

    def get(self, request, *args, **kwargs):
        return self.render_to_response({'aform': AForm(prefix='aform_pre'), 'bform': BForm(prefix='bform_pre')})

    def post(self, request, *args, **kwargs):
        aform = _get_form(request, AForm, 'aform_pre')
        bform = _get_form(request, BForm, 'bform_pre')
        if aform.is_bound and aform.is_valid():
            # Process aform and render response
        elif bform.is_bound and bform.is_valid():
            # Process bform and render response
        return self.render_to_response({'aform': aform, 'bform': bform})

# mytemplate.html
<form action="" method="post">
    {% csrf_token %}
    {{ aform.as_p }}
    <input type="submit" name="{{aform.prefix}}" value="Submit" />
    {{ bform.as_p }}
    <input type="submit" name="{{bform.prefix}}" value="Submit" />
</form>

Get line number while using grep

Line numbers are printed with grep -n:

grep -n pattern file.txt

To get only the line number (without the matching line), one may use cut:

grep -n pattern file.txt | cut -d : -f 1

Lines not containing a pattern are printed with grep -v:

grep -v pattern file.txt

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

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

Just do git checkout path/to/file-I-want-to-bring-back.txt

How do I make a matrix from a list of vectors in R?

One option is to use do.call():

 > do.call(rbind, a)
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

How to click a href link using Selenium

You can use this method:

For the links if you use linkText(); it is more effective than the any other locator.

driver.findElement(By.linkText("App Configuration")).click();

How to access JSON Object name/value?

Here is a friendly piece of advice. Use something like Chrome Developer Tools or Firebug for Firefox to inspect your Ajax calls and results.

You may also want to invest some time in understanding a helper library like Underscore, which complements jQuery and gives you 60+ useful functions for manipulating data objects with JavaScript.

width:auto for <input> fields

Answer 1 - "response" gave a nice answer/link for it. To put it in short, "auto" is the default, so it is like removing any changes in the width of an element

Answer 2 - use width: 100% instead. It will fill the 100% of the parent container, in this case, the "form".

How do I make the text box bigger in HTML/CSS?

If you want to make them a lot bigger, like for multiple lines of input, you may want to use a textarea tag instead of the input tag. This allows you to put in number of rows and columns you want on your textarea without messing with css (e.g. <textarea rows="2" cols="25"></textarea>).

Text areas are resizable by default. If you want to disable that, just use the resize css rule:

#signin textarea {
    resize: none;
}

A simple solution to your question about default text that disappears when the user clicks is to use the placeholder attribute. This will work for <input> tags as well.

<textarea rows="2" cols="25" placeholder="This is the default text"></textarea>

This text will disappear when the user enters information rather than when they click, but that is common functionality for this kind of thing.

Adding css class through aspx code behind

BtnAdd.CssClass = "BtnCss";

BtnCss should be present in your Css File.

(reference of that Css File name should be added to the aspx if needed)

How do I create a self-signed certificate for code signing on Windows?

As stated in the answer, in order to use a non deprecated way to sign your own script, one should use New-SelfSignedCertificate.

  1. Generate the key:
New-SelfSignedCertificate -DnsName [email protected] -Type CodeSigning -CertStoreLocation cert:\CurrentUser\My
  1. Export the certificate without the private key:
Export-Certificate -Cert (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)[0] -FilePath code_signing.crt

The [0] will make this work for cases when you have more than one certificate... Obviously make the index match the certificate you want to use... or use a way to filtrate (by thumprint or issuer).

  1. Import it as Trusted Publisher
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\TrustedPublisher
  1. Import it as a Root certificate authority.
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\Root
  1. Sign the script (assuming here it's named script.ps1, fix the path accordingly).
Set-AuthenticodeSignature .\script.ps1 -Certificate (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)

Obviously once you have setup the key, you can simply sign any other scripts with it.
You can get more detailed information and some troubleshooting help in this article.

How to detect simple geometric shapes using OpenCV

If you have only these regular shapes, there is a simple procedure as follows :

  1. Find Contours in the image ( image should be binary as given in your question)
  2. Approximate each contour using approxPolyDP function.
  3. First, check number of elements in the approximated contours of all the shapes. It is to recognize the shape. For eg, square will have 4, pentagon will have 5. Circles will have more, i don't know, so we find it. ( I got 16 for circle and 9 for half-circle.)
  4. Now assign the color, run the code for your test image, check its number, fill it with corresponding colors.

Below is my example in Python:

import numpy as np
import cv2

img = cv2.imread('shapes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(gray,127,255,1)

contours,h = cv2.findContours(thresh,1,2)

for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    print len(approx)
    if len(approx)==5:
        print "pentagon"
        cv2.drawContours(img,[cnt],0,255,-1)
    elif len(approx)==3:
        print "triangle"
        cv2.drawContours(img,[cnt],0,(0,255,0),-1)
    elif len(approx)==4:
        print "square"
        cv2.drawContours(img,[cnt],0,(0,0,255),-1)
    elif len(approx) == 9:
        print "half-circle"
        cv2.drawContours(img,[cnt],0,(255,255,0),-1)
    elif len(approx) > 15:
        print "circle"
        cv2.drawContours(img,[cnt],0,(0,255,255),-1)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Below is the output:

enter image description here

Remember, it works only for regular shapes.

Alternatively to find circles, you can use houghcircles. You can find a tutorial here.

Regarding iOS, OpenCV devs are developing some iOS samples this summer, So visit their site : www.code.opencv.org and contact them.

You can find slides of their tutorial here : http://code.opencv.org/svn/gsoc2012/ios/trunk/doc/CVPR2012_OpenCV4IOS_Tutorial.pdf

How to view the roles and permissions granted to any database user in Azure SQL server instance?

Building on @tmullaney 's answer, you can also left join in the sys.objects view to get insight when explicit permissions have been granted on objects. Make sure to use the LEFT join:

SELECT DISTINCT pr.principal_id, pr.name AS [UserName], pr.type_desc AS [User_or_Role], pr.authentication_type_desc AS [Auth_Type], pe.state_desc,
    pe.permission_name, pe.class_desc, o.[name] AS 'Object' 
    FROM sys.database_principals AS pr 
    JOIN sys.database_permissions AS pe ON pe.grantee_principal_id = pr.principal_id
    LEFT JOIN sys.objects AS o on (o.object_id = pe.major_id)

Batch file to move files to another directory

Try:

move "C:\files\*.txt" "C:\txt"

Rotate label text in seaborn factorplot

This is still a matplotlib object. Try this:

# <your code here>
locs, labels = plt.xticks()
plt.setp(labels, rotation=45)

Replace new lines with a comma delimiter with Notepad++?

fapDaddy's answer using a macro pointed me in the right direction.

Here's precisely what worked for me.

  1. Place the cursor after the first data item. enter image description here

  2. Click 'Macro > Start Recording' in the menu. enter image description here

  3. Type this sequence: Comma, Space, Delete, End. enter image description here

  4. Click 'Macro > Stop recording' in the menu. enter image description here

  5. Click 'Macro > Run a Macro Multiple Times...' in the menu. enter image description here

  6. Click 'Run until the end of file' and click 'Run'. enter image description here

  7. Remove any trailing characters. enter image description here

  8. Done!

enter image description here

Upload video files via PHP and save them in appropriate folder and have a database entry

sample code:

<em><b>
<h2>Upload,Save and Download video </h2>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="video"/>
<input type="submit" name="submit" value="Upload"/></b>
</form></em>

<?php>
include("connect.php");
$errors=1;
//Targeting Folder
$target="videos/";
if(isset($_POST['submit'])){
//Targeting Folder 
$target=$target.basename($_FILES['video']['name']);
//Getting Selected video Type
$type=pathinfo($target,PATHINFO_EXTENSION);
 //Allow Certain File Format To Upload
 if($type!='mp4' && $type!='3gp' && $type!='avi'){
  echo "Only mp4,3gp,avi file format are allowed to Upload";
  $errors=0;
 }
 //checking for Exsisting video Files
  if(file_exists($target)){
   echo "File Exist";
   $errors=0;
   }
  $filesize=$_FILES['video']['size'];
  if($filesize>250*2000000){
  echo 'You Can not Upload Large File(more than 500MB) by Default ini setting..<a     href="http://www.codenair.com/2018/03/how-to-upload-large-file-in-php.html">How to   upload large file in php</a>'; 
    $errors=0;
    }
   if($errors == 0){
   echo ' Your File Not Uploaded';
    }else{
 //Moving The video file to Desired Directory
  $uplaod_success=move_uploaded_file($_FILES['video']['tmp_name'],$target);
  if($uplaod_success){
  //Getting Selected video Information
    $name=$_FILES['video']['name'];
    $size=$_FILES['video']['size'];
    $result=mysqli_query($con,"INSERT INTO VIdeos           (name,size,type)VALUES('".$name."','".$size."','".$type."')");
    if($result==TRUE){
    echo "Your video '$name' Successfully Upload and Information Saved Our  Database";
    }
   }
  }
  }
 ?>

How to unblock with mysqladmin flush hosts

You can easily restart your MySql service. This kicks the error off.

What is a lambda (function)?

In context of CS a lambda function is an abstract mathematical concept that tackles a problem of symbolic evaluation of mathematical expressions. In that context a lambda function is the same as a lambda term.

But in programming languages it's something different. It's a piece of code that is declared "in place", and that can be passed around as a "first-class citizen". This concept appeared to be useful so that it came into almost all popular modern programming languages (see lambda functions everwhere post).

Eclipse - java.lang.ClassNotFoundException

This was my solution to the problem. Of course, many things can cause it to occur. For me it was that Maven2 (not the plugin for Eclipse) was setting the eclipse profile up to use a different builder (aspectJ) but I did not have the plugin in eclipse./

http://rbtech.blogspot.com/2009/09/eclipse-galileo-javalangclassnotfoundex.html

Cheers Ramon Buckland

angular ng-repeat in reverse

I had gotten frustrated with this problem myself and so I modified the filter that was created by @Trevor Senior as I was running into an issue with my console saying that it could not use the reverse method. I also, wanted to keep the integrity of the object because this is what Angular is originally using in a ng-repeat directive. In this case I used the input of stupid (key) because the console will get upset saying there are duplicates and in my case I needed to track by $index.

Filter:

angular.module('main').filter('reverse', function() {
    return function(stupid, items) {
    var itemss = items.files;
    itemss = itemss.reverse();  
    return items.files = itemss; 
  };
});

HTML: <div ng-repeat="items in items track by $index | reverse: items">

Euclidean distance of two vectors

If you want to use less code, you can also use the norm in the stats package (the 'F' stands for Forbenius, which is the Euclidean norm):

norm(matrix(x1-x2), 'F')

While this may look a bit neater, it's not faster. Indeed, a quick test on very large vectors shows little difference, though so12311's method is slightly faster. We first define:

set.seed(1234)
x1 <- rnorm(300000000)
x2 <- rnorm(300000000)

Then testing for time yields the following:

> system.time(a<-sqrt(sum((x1-x2)^2)))
user  system elapsed 
1.02    0.12    1.18 
> system.time(b<-norm(matrix(x1-x2), 'F'))
user  system elapsed 
0.97    0.33    1.31 

What HTTP status response code should I use if the request is missing a required parameter?

You can send a 400 Bad Request code. It's one of the more general-purpose 4xx status codes, so you can use it to mean what you intend: the client is sending a request that's missing information/parameters that your application requires in order to process it correctly.

How to declare a global variable in React?

Is not recommended but.... you can use componentWillMount from your app class to add your global variables trough it... a bit like so:

componentWillMount: function () {
    window.MyVars = {
        ajax: require('../helpers/ajax.jsx'),
        utils: require('../helpers/utils.jsx')
    };
}

still consider this a hack... but it will get your job done

btw componentWillMount executes once before rendering, see more here: https://reactjs.org/docs/react-component.html#mounting-componentwillmount

notifyDataSetChanged example

I know this is a late response but I was facing a similar issue and I managed to solve it by using notifyDataSetChanged() in the right place.

So my situation was as follows.

I had to update a listview in an action bar tab (fragment) with contents returned from a completely different activity. Initially however, the listview would not reflect any changes. However, when I clicked another tab and then returned to the desired tab,the listview would be updated with the correct content from the other activity. So to solve this I used notifyDataSetChanged() of the action bar adapter in the code of the activity which had to return the data.

This is the code snippet which I used in the activity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) 
    {
        case R.id.action_new_forward:

            FragmentTab2.mListAdapter.notifyDataSetChanged();//this updates the adapter in my action bar tab
            Intent ina = new Intent(getApplicationContext(), MainActivity.class);
            ina.putExtra("stra", values1);
            startActivity(ina);// This is the code to start the parent activity of my action bar tab(fragment).
    }
}

This activity would return some data to FragmentTab2 and it would directly update my listview in FragmentTab2.

Hope someone finds this useful!

How to copy to clipboard using Access/VBA?

User Leigh Webber on the social.msdn.microsoft.com site posted VBA code implementing an easy-to-use clipboard interface that uses the Windows API:

http://social.msdn.microsoft.com/Forums/en/worddev/thread/ee9e0d28-0f1e-467f-8d1d-1a86b2db2878

You can get Leigh Webber's source code here

If this link doesn't go through, search for "A clipboard object for VBA" in the Office Dev Center > Microsoft Office for Developers Forums > Word for Developers section.

I created the two classes, ran his test cases, and it worked perfectly inside Outlook 2007 SP3 32-bit VBA under Windows 7 64-bit. It will most likely work for Access. Tip: To rename classes, select the class in the VBA 'Project' window, then click 'View' on the menu bar and click 'Properties Window' (or just hit F4).

With his classes, this is what it takes to copy to/from the clipboard:

Dim myClipboard As New vbaClipboard  ' Create clipboard

' Copy text to clipboard as ClipboardFormat TEXT (CF_TEXT)    
myClipboard.SetClipboardText "Text to put in clipboard", "CF_TEXT"    

' Retrieve clipboard text in CF_TEXT format (CF_TEXT = 1)
mytxt = myClipboard.GetClipboardText(1)

He also provides other functions for manipulating the clipboard.

It also overcomes 32KB MSForms_DataObject.SetText limitation - the main reason why SetText often fails. However, bear in mind that, unfortunatelly, I haven't found a reference on Microsoft recognizing this limitation.

-Jim

Git: add vs push vs commit

I find this image very meaningful :

enter image description here

(from : Oliver Steele -My Git Workflow (2008) )

List files in local git repo?

Try this command:

git ls-files 

This lists all of the files in the repository, including those that are only staged but not yet committed.

http://www.kernel.org/pub/software/scm/git/docs/git-ls-files.html

How is the default submit button on an HTML form determined?

When you have multiple submit buttons in a single form and a user presses the ENTER key to submit the form from a text field, this code overrides default functionality, by calling the submit event on the form from the key press event. Here is that code:

$('form input').keypress(function(e){

    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)){ $(e.target).closest('form').submit(); return false; }
    else return true;

});

Check if string ends with one of the strings from a list

I just came across this, while looking for something else.

I would recommend to go with the methods in the os package. This is because you can make it more general, compensating for any weird case.

You can do something like:

import os

the_file = 'aaaa/bbbb/ccc.ddd'

extensions_list = ['ddd', 'eee', 'fff']

if os.path.splitext(the_file)[-1] in extensions_list:
    # Do your thing.

Image inside div has extra space below the image

Quick fix:

To remove the gap under the image, you can:

  • Set the vertical-align property of the image to vertical-align: bottom; vertical-align: top; or vertical-align: middle;
  • Set the display property of the image to display:block;

See the following code for a live demo:

_x000D_
_x000D_
#vAlign img {_x000D_
  vertical-align :bottom;_x000D_
}_x000D_
#block img{_x000D_
  display:block;_x000D_
}_x000D_
_x000D_
div {border: 1px solid red;width:100px;}_x000D_
img {width:100px;}
_x000D_
<p>No fix:</p>_x000D_
<div><img src="http://i.imgur.com/RECDV24.jpg" /></div>_x000D_
_x000D_
<p>With vertical-align:bottom; on image:</p>_x000D_
<div id="vAlign"><img src="http://i.imgur.com/RECDV24.jpg" /></div>_x000D_
_x000D_
<p>With display:block; on image:</p>_x000D_
<div id="block"><img src="http://i.imgur.com/RECDV24.jpg" /></div>
_x000D_
_x000D_
_x000D_


Explanation: why is there a gap under the image?

The gap or extra space under the image isn't a bug or issue, it is the default behaviour. The root cause is that images are replaced elements (see MDN replaced elements). This allows them to "act like image" and have their own intrinsic dimensions, aspect ratio....
Browsers compute their display property to inline but they give them a special behaviour which makes them closer to inline-block elements (as you can vertical align them, give them a height, top/bottom margin and padding, transforms ...).

This also means that:

<img> has no baseline, so when images are used in an inline formatting context with vertical-align: baseline, the bottom of the image will be placed on the text baseline.
(source: MDN, emphasis mine)

As browsers by default compute the vertical-align property to baseline, this is the default behaviour. The following image shows where the baseline is located on text:

Location of the baseline on text (Image source)

Baseline aligned elements need to keep space for the descenders that extend below the baseline (like j, p, g ...) as you can see in the above image. In this configuration, the bottom of the image is aligned on the baseline as you can see in this example:

_x000D_
_x000D_
div{border:1px solid red;font-size:30px;}_x000D_
img{width:100px;height:auto;}
_x000D_
<div>_x000D_
  <img src="http://i.imgur.com/RECDV24.jpg" />jpq are letters with descender_x000D_
</div>
_x000D_
_x000D_
_x000D_


This is why the default behaviour of the <img> tag creates a gap at the bottom of it's container and why changing the vertical-align property or the display property removes it as in the following demo:

_x000D_
_x000D_
div {width: 100px;border: 1px solid red;}_x000D_
img {width: 100px;height: auto;}_x000D_
_x000D_
.block img{_x000D_
  display:block;_x000D_
}_x000D_
.bottom img{_x000D_
  vertical-align:bottom;_x000D_
}
_x000D_
<p>Default:</p>_x000D_
<div>_x000D_
  <img src="http://i.imgur.com/RECDV24.jpg" />_x000D_
</div>_x000D_
<p>With display:block;</p>_x000D_
<div class="block">_x000D_
  <img src="http://i.imgur.com/RECDV24.jpg" />_x000D_
</div>_x000D_
<p>With vertical-align:bottom;</p>_x000D_
<div class="bottom">_x000D_
  <img src="http://i.imgur.com/RECDV24.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Sass - Converting Hex to RGBa for background opacity

SASS has a built-in rgba() function to evaluate values.

rgba($color, $alpha)

E.g.

rgba(#00aaff, 0.5) => rgba(0, 170, 255, 0.5)

An example using your own variables:

$my-color: #00aaff;
$my-opacity: 0.5;

.my-element {
  color: rgba($my-color, $my-opacity);
}

Outputs:

.my-element {
  color: rgba(0, 170, 255, 0.5);
}

Invoking a jQuery function after .each() has completed

Ok, this might be a little after the fact, but .promise() should also achieve what you're after.

Promise documentation

An example from a project i'm working on:

$( '.panel' )
    .fadeOut( 'slow')
    .promise()
    .done( function() {
        $( '#' + target_panel ).fadeIn( 'slow', function() {});
    });

:)

python mpl_toolkits installation issue

I can't comment due to the lack of reputation, but if you are on arch linux, you should be able to find the corresponding libraries on the arch repositories directly. For example for mpl_toolkits.basemap:

pacman -S python-basemap

How to initialize a list with constructor?

Are you looking for this?

ContactNumbers = new List<ContactNumber>(){ new ContactNumber("555-5555"),
                                            new ContactNumber("555-1234"),
                                            new ContactNumber("555-5678") };

NodeJS/express: Cache and 304 status code

As you said, Safari sends Cache-Control: max-age=0 on reload. Express (or more specifically, Express's dependency, node-fresh) considers the cache stale when Cache-Control: no-cache headers are received, but it doesn't do the same for Cache-Control: max-age=0. From what I can tell, it probably should. But I'm not an expert on caching.

The fix is to change (what is currently) line 37 of node-fresh/index.js from

if (cc && cc.indexOf('no-cache') !== -1) return false;  

to

if (cc && (cc.indexOf('no-cache') !== -1 ||
  cc.indexOf('max-age=0') !== -1)) return false;

I forked node-fresh and express to include this fix in my project's package.json via npm, you could do the same. Here are my forks, for example:

https://github.com/stratusdata/node-fresh https://github.com/stratusdata/express#safari-reload-fix

The safari-reload-fix branch is based on the 3.4.7 tag.

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

If you using windows authentication make sure that password of the user hasn't expired. An expired password can explain this error. This was the problem in my case.

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

On Windows the easiest way is to use the program portecle.

  1. Download and install portecle.
  2. First make 100% sure you know which JRE or JDK is being used to run your program. On a 64 bit Windows 7 there could be quite a few JREs. Process Explorer can help you with this or you can use: System.out.println(System.getProperty("java.home"));
  3. Copy the file JAVA_HOME\lib\security\cacerts to another folder.
  4. In Portecle click File > Open Keystore File
  5. Select the cacerts file
  6. Enter this password: changeit
  7. Click Tools > Import Trusted Certificate
  8. Browse for the file mycertificate.pem
  9. Click Import
  10. Click OK for the warning about the trust path.
  11. Click OK when it displays the details about the certificate.
  12. Click Yes to accept the certificate as trusted.
  13. When it asks for an alias click OK and click OK again when it says it has imported the certificate.
  14. Click save. Don’t forget this or the change is discarded.
  15. Copy the file cacerts back where you found it.

On Linux:

You can download the SSL certificate from a web server that is already using it like this:

$ echo -n | openssl s_client -connect www.example.com:443 | \
   sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/examplecert.crt

Optionally verify the certificate information:

$ openssl x509 -in /tmp/examplecert.crt -text

Import the certificate into the Java cacerts keystore:

$ keytool -import -trustcacerts -keystore /opt/java/jre/lib/security/cacerts \
   -storepass changeit -noprompt -alias mycert -file /tmp/examplecert.crt

angular 4: *ngIf with multiple conditions

You got a ninja ')'.

Try :

<div *ngIf="currentStatus !== 'open' || currentStatus !== 'reopen'">

How to echo in PHP, HTML tags

<?php

echo '<div>
 <h3><a href="#">First</a></h3>
 <div>Lorem ipsum dolor sit amet.</div>
</div>
<div>';

?>

Just put it in single quotes.

SQL User Defined Function Within Select

Yes, you can do almost that:

SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays
FROM account a
WHERE...

How to change the application launcher icon on Flutter?

I have changed it in the following steps:

1) please add this dependency on your pubspec.yaml page

 dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_launcher_icons: ^0.7.4

2) you have to upload an image/icon on your project which you want to see as a launcher icon. (i have created a folder name:image in my project then upload the logo.png in the image folder). Now you have to add the below codes and paste your image path on image_path: in pubspec.yaml page.

flutter_icons:
  image_path: "images/logo.png"
  android: true
  ios: true

3) Go to terminal and execute this command:

flutter pub get

4) After executing the command then enter below command:

flutter pub run flutter_launcher_icons:main

5) Done

N.B: (of course add an updated dependency from

https://pub.dev/packages/flutter_launcher_icons#-installing-tab-

)

How to align this span to the right of the div?

Working with floats is bit messy:

This as many other 'trivial' layout tricks can be done with flexbox.

   div.container {
     display: flex;
     justify-content: space-between;
   }

In 2017 I think this is preferred solution (over float) if you don't have to support legacy browsers: https://caniuse.com/#feat=flexbox

Check fiddle how different float usages compares to flexbox ("may include some competing answers"): https://jsfiddle.net/b244s19k/25/. If you still need to stick with float I recommended third version of course.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

How to recover MySQL database from .myd, .myi, .frm files

You can copy the files into an appropriately named subdirectory directory of the data folder as long as it is the EXACT same version of mySQL and you have retained all of the associated files in that directory. If you don't have all the files, I'm pretty sure you're going to have issues.

database vs. flat files

What types of files is not mentioned. If they're media files, go ahead with flat files. You probably just need a DB for tags and some way to associate the "external BLOBs" to the records in the DB. But if full text search is something you need, there's no other way to go but migrate to a full DB.

Another thing, your filesystem might provide the ceiling as far as number of physical files are concerned.

Set disable attribute based on a condition for Html.TextBoxFor

One simple approach I have used is conditional rendering:

@(Model.ExpireDate == null ? 
  @Html.TextBoxFor(m => m.ExpireDate, new { @disabled = "disabled" }) : 
  @Html.TextBoxFor(m => m.ExpireDate)
)

Box shadow for bottom side only

Specify negative value to spread value. This works for me:

box-shadow: 0 2px 3px -1px rgba(0, 0, 0, 0.1);

jquery .on() method with load event

As the other have mentioned, the load event does not bubble. Instead you can manually trigger a load-like event with a custom event:

$('#item').on('namespace/onload', handleOnload).trigger('namespace/onload')

If your element is already listening to a change event:

$('#item').on('change', handleChange).trigger('change')

I find this works well. Though, I stick to custom events to be more explicit and avoid side effects.

How do I trap ctrl-c (SIGINT) in a C# console app

This question is very similar to:

Capture console exit C#

Here is how I solved this problem, and dealt with the user hitting the X as well as Ctrl-C. Notice the use of ManualResetEvents. These will cause the main thread to sleep which frees the CPU to process other threads while waiting for either exit, or cleanup. NOTE: It is necessary to set the TerminationCompletedEvent at the end of main. Failure to do so causes unnecessary latency in termination due to the OS timing out while killing the application.

namespace CancelSample
{
    using System;
    using System.Threading;
    using System.Runtime.InteropServices;

    internal class Program
    {
        /// <summary>
        /// Adds or removes an application-defined HandlerRoutine function from the list of handler functions for the calling process
        /// </summary>
        /// <param name="handler">A pointer to the application-defined HandlerRoutine function to be added or removed. This parameter can be NULL.</param>
        /// <param name="add">If this parameter is TRUE, the handler is added; if it is FALSE, the handler is removed.</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(ConsoleCloseHandler handler, bool add);

        /// <summary>
        /// The console close handler delegate.
        /// </summary>
        /// <param name="closeReason">
        /// The close reason.
        /// </param>
        /// <returns>
        /// True if cleanup is complete, false to run other registered close handlers.
        /// </returns>
        private delegate bool ConsoleCloseHandler(int closeReason);

        /// <summary>
        ///  Event set when the process is terminated.
        /// </summary>
        private static readonly ManualResetEvent TerminationRequestedEvent;

        /// <summary>
        /// Event set when the process terminates.
        /// </summary>
        private static readonly ManualResetEvent TerminationCompletedEvent;

        /// <summary>
        /// Static constructor
        /// </summary>
        static Program()
        {
            // Do this initialization here to avoid polluting Main() with it
            // also this is a great place to initialize multiple static
            // variables.
            TerminationRequestedEvent = new ManualResetEvent(false);
            TerminationCompletedEvent = new ManualResetEvent(false);
            SetConsoleCtrlHandler(OnConsoleCloseEvent, true);
        }

        /// <summary>
        /// The main console entry point.
        /// </summary>
        /// <param name="args">The commandline arguments.</param>
        private static void Main(string[] args)
        {
            // Wait for the termination event
            while (!TerminationRequestedEvent.WaitOne(0))
            {
                // Something to do while waiting
                Console.WriteLine("Work");
            }

            // Sleep until termination
            TerminationRequestedEvent.WaitOne();

            // Print a message which represents the operation
            Console.WriteLine("Cleanup");

            // Set this to terminate immediately (if not set, the OS will
            // eventually kill the process)
            TerminationCompletedEvent.Set();
        }

        /// <summary>
        /// Method called when the user presses Ctrl-C
        /// </summary>
        /// <param name="reason">The close reason</param>
        private static bool OnConsoleCloseEvent(int reason)
        {
            // Signal termination
            TerminationRequestedEvent.Set();

            // Wait for cleanup
            TerminationCompletedEvent.WaitOne();

            // Don't run other handlers, just exit.
            return true;
        }
    }
}

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

And if you are using typescript (gulpfile.ts) then do this for yargs (building on @Caio Cunha's excellent answer https://stackoverflow.com/a/23038290/1019307 and other comments above):

Install

npm install --save-dev yargs

typings install dt~yargs --global --save

.ts files

Add this to the .ts files:

import { argv } from 'yargs';

...

  let debug: boolean = argv.debug;

This has to be done in each .ts file individually (even the tools/tasks/project files that are imported into the gulpfile.ts/js).

Run

gulp build.dev --debug

Or under npm pass the arg through to gulp:

npm run build.dev -- --debug

How to split string using delimiter char using T-SQL?

You simply need to do a SUBSTR on the string in col3....

    Select col1, col2, REPLACE(substr(col3, instr(col3, 'Client Name'), 
    (instr(col3, '|', instr(col3, 'Client Name')  -
    instr(col3, 'Client Name'))
    ),
'Client Name = ',
'')
    from Table01 

And yes, that is a bad DB design for the reasons stated in the original issue

Delete all lines beginning with a # from a file

The opposite of Raymond's solution:

sed -n '/^#/!p'

"don't print anything, except for lines that DON'T start with #"

Url.Action parameters?

The following is the correct overload (in your example you are missing a closing } to the routeValues anonymous object so your code will throw an exception):

<a href="<%: Url.Action("GetByList", "Listing", new { name = "John", contact = "calgary, vancouver" }) %>">
    <span>People</span>
</a>

Assuming you are using the default routes this should generate the following markup:

<a href="/Listing/GetByList?name=John&amp;contact=calgary%2C%20vancouver">
    <span>People</span>
</a>

which will successfully invoke the GetByList controller action passing the two parameters:

public ActionResult GetByList(string name, string contact) 
{
    ...
}

string.split - by multiple character delimiter

Regex.Split("abc][rfd][5][,][.", @"\]\]");

Group by & count function in sqlalchemy

If you are using Table.query property:

from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()

If you are using session.query() method (as stated in miniwark's answer):

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Pass a password to ssh in pure bash

You can not specify the password from the command line but you can do either using ssh keys or using sshpass as suggested by John C. or using a expect script.

To use sshpass, you need to install it first. Then

sshpass -f <(printf '%s\n' your_password) ssh user@hostname

instead of using sshpass -p your_password. As mentioned by Charles Duffy in the comments, it is safer to supply the password from a file or from a variable instead of from command line.

BTW, a little explanation for the <(command) syntax. The shell executes the command inside the parentheses and replaces the whole thing with a file descriptor, which is connected to the command's stdout. You can find more from this answer https://unix.stackexchange.com/questions/156084/why-does-process-substitution-result-in-a-file-called-dev-fd-63-which-is-a-pipe

how to create a logfile in php?

Use below function

// Enable error reporting
ini_set('display_errors', 1);
//Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//error_reporting(E_ALL & ~E_NOTICE);
// Tell php where your custom php error log is
ini_set('error_log', 'php_error.log');

$dateTime=date("Y-m-d H:i:s");
$ip= $_SERVER['REMOTE_ADDR'];
$errorString="Error occured on time $dateTime by ip $ip";
$php_error_msg.=$errorString;
// Append the error message to the php-error log
//error_log($php_error_msg);
error_log("A custom error has been triggered",1,"email_address","From: email_address");

Above function will create a log in file php_error with proper description and email will be sent.

SQL query for today's date minus two months

SELECT COUNT(1) FROM FB 
WHERE Dte > DATE_SUB(now(), INTERVAL 2 MONTH)

Can’t delete docker image with dependent child images

When i want to remove some unused image with name "<none>" in docker i face with the problem unable to delete a354bbc7c9b7 (cannot be forced) - image has dependent child images.So for solving this problem:

sudo docker ps -a

CONTAINER ID        IMAGE                       COMMAND                  CREATED             STATUS                         PORTS                                              NAMES
01ee1276bbe0        lizard:1                    "/bin/sh -c 'java ..."   About an hour ago   Exited (1) About an hour ago                                                      objective_lewin
49d73d8fb023        javaapp:latest              "/usr/bin/java -ja..."   19 hours ago        Up 19 hours                    0.0.0.0:8091->8091/tcp                             pedantic_bell
405fd452c788        javaapp:latest              "/usr/bin/java -ja..."   19 hours ago        Created                                                                           infallible_varahamihira
532257a8b705        javaapp:latest              "/usr/bin/java -ja..."   19 hours ago        Created                                                                           demo-default
9807158b3fd5        javaapp:latest              "/usr/bin/java -ja..."   19 hours ago        Created                                                                           xenodochial_kilby
474930241afa        jenkins                     "/bin/tini -- /usr..."   13 days ago         Up 4 days                      0.0.0.0:8080->8080/tcp, 0.0.0.0:50000->50000/tcp   myjenkins
563d8c34682f        mysql/mysql-server:latest   "/entrypoint.sh my..."   3 weeks ago         Up 4 days (healthy)            0.0.0.0:3306->3306/tcp, 33060/tcp                  mymysql
b4ca73d45d20        phpmyadmin/phpmyadmin       "/run.sh phpmyadmin"     4 weeks ago         Exited (0) 3 weeks ago                                                            phpmyadmin

you can see that i have several Images with name javaapp:latest and different container name. So, i killed and remove all container of "javaapp:latest" container with:

sudo docker stop "containerName"

sudo docker rm "containrName"

Then

sudo docker rmi -f "imageId"

So i can remove all the images with name "<none>"

goodluck

Linux/Unix command to determine if process is running?

I use pgrep -l httpd but not sure it is present on any platform...
Who can confirm on OSX?

Keyboard shortcut to "untab" (move a block of code to the left) in eclipse / aptana?

Here is a general answer for untab :-

In Python IDLE :- Ctrl + [

In elipse :- Shitft + Tab

In Visual Studio :- Shift+ Tab

Determine number of pages in a PDF file

You'll need a PDF API for C#. iTextSharp is one possible API, though better ones might exist.

iTextSharp Example

You must install iTextSharp.dll as a reference. Download iTextsharp from SourceForge.net This is a complete working program using a console application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace GetPages_PDF
{
  class Program
{
    static void Main(string[] args)
      {
       // Right side of equation is location of YOUR pdf file
        string ppath = "C:\\aworking\\Hawkins.pdf";
        PdfReader pdfReader = new PdfReader(ppath);
        int numberOfPages = pdfReader.NumberOfPages;
        Console.WriteLine(numberOfPages);
        Console.ReadLine();
      }
   }
}

How to install requests module in Python 3.4, instead of 2.7

On Windows with Python v3.6.5

py -m pip install requests

Concatenate string with field value in MySQL

SELECT ..., CONCAT( 'category_id=', tableOne.category_id) as query2  FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = query2

How to get the name of the current Windows user in JavaScript

JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.

JavaScript will not be able to determine your Windows user name.

How to multiply duration by integer?

int32 and time.Duration are different types. You need to convert the int32 to a time.Duration, such as time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond).

Proper use of errors

Someone posted this link to the MDN in a comment, and I think it was very helpful. It describes things like ErrorTypes very thoroughly.

EvalError --- Creates an instance representing an error that occurs regarding the global function eval().

InternalError --- Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".

RangeError --- Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.

ReferenceError --- Creates an instance representing an error that occurs when de-referencing an invalid reference.

SyntaxError --- Creates an instance representing a syntax error that occurs while parsing code in eval().

TypeError --- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.

URIError --- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.

event.preventDefault() function not working in IE

I was helped by a method with a function check. This method works in IE8

if(typeof e.preventDefault == 'function'){
  e.preventDefault();
} else {
  e.returnValue = false;
}

How do I open the "front camera" on the Android platform?

private Camera openFrontFacingCameraGingerbread() {
    int cameraCount = 0;
    Camera cam = null;
    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    cameraCount = Camera.getNumberOfCameras();
    for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
        Camera.getCameraInfo(camIdx, cameraInfo);
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            try {
                cam = Camera.open(camIdx);
            } catch (RuntimeException e) {
                Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
            }
        }
    }

    return cam;
}

Add the following permissions in the AndroidManifest.xml file:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />

Note: This feature is available in Gingerbread(2.3) and Up Android Version.

Regex for Comma delimited list

The following will match any comma delimited word/digit/space combination

(((.)*,)*)(.)*

to remove first and last element in array

This can be done with lodash _.tail and _.dropRight:

_x000D_
_x000D_
var fruits = ["Banana", "Orange", "Apple", "Mango"];_x000D_
console.log(_.dropRight(_.tail(fruits)));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Why should I prefer to use member initialization lists?

For POD class members, it makes no difference, it's just a matter of style. For class members which are classes, then it avoids an unnecessary call to a default constructor. Consider:

class A
{
public:
    A() { x = 0; }
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B()
    {
        a.x = 3;
    }
private:
    A a;
};

In this case, the constructor for B will call the default constructor for A, and then initialize a.x to 3. A better way would be for B's constructor to directly call A's constructor in the initializer list:

B()
  : a(3)
{
}

This would only call A's A(int) constructor and not its default constructor. In this example, the difference is negligible, but imagine if you will that A's default constructor did more, such as allocating memory or opening files. You wouldn't want to do that unnecessarily.

Furthermore, if a class doesn't have a default constructor, or you have a const member variable, you must use an initializer list:

class A
{
public:
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B() : a(3), y(2)  // 'a' and 'y' MUST be initialized in an initializer list;
    {                 // it is an error not to do so
    }
private:
    A a;
    const int y;
};

Changing the cursor in WPF sometimes works, sometimes doesn't

One way we do this in our application is using IDisposable and then with using(){} blocks to ensure the cursor is reset when done.

public class OverrideCursor : IDisposable
{

  public OverrideCursor(Cursor changeToCursor)
  {
    Mouse.OverrideCursor = changeToCursor;
  }

  #region IDisposable Members

  public void Dispose()
  {
    Mouse.OverrideCursor = null;
  }

  #endregion
}

and then in your code:

using (OverrideCursor cursor = new OverrideCursor(Cursors.Wait))
{
  // Do work...
}

The override will end when either: the end of the using statement is reached or; if an exception is thrown and control leaves the statement block before the end of the statement.

Update

To prevent the cursor flickering you can do:

public class OverrideCursor : IDisposable
{
  static Stack<Cursor> s_Stack = new Stack<Cursor>();

  public OverrideCursor(Cursor changeToCursor)
  {
    s_Stack.Push(changeToCursor);

    if (Mouse.OverrideCursor != changeToCursor)
      Mouse.OverrideCursor = changeToCursor;
  }

  public void Dispose()
  {
    s_Stack.Pop();

    Cursor cursor = s_Stack.Count > 0 ? s_Stack.Peek() : null;

    if (cursor != Mouse.OverrideCursor)
      Mouse.OverrideCursor = cursor;
  }

}

ASP.Net 2012 Unobtrusive Validation with jQuery

Add a reference to Microsoft.JScript in your application in your web.config as below :

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="Microsoft.JScript, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>
  </appSettings>
</configuration>

How to skip to next iteration in jQuery.each() util?

Dont forget that you can sometimes just fall off the end of the block to get to the next iteration:

$(".row").each( function() {
    if ( ! leaveTheLoop ) {
        ... do stuff here ...
    }
});

Rather than actually returning like this:

$(".row").each( function() {
    if ( leaveTheLoop ) 
        return; //go to next iteration in .each()
    ... do stuff here ...
});

How to make a new List in Java

Let me summarize and add something:

JDK

1. new ArrayList<String>();
2. Arrays.asList("A", "B", "C")

Guava

1. Lists.newArrayList("Mike", "John", "Lesly");
2. Lists.asList("A","B", new String [] {"C", "D"});

Immutable List

1. Collections.unmodifiableList(new ArrayList<String>(Arrays.asList("A","B")));
2. ImmutableList.builder()                                      // Guava
            .add("A")
            .add("B").build();
3. ImmutableList.of("A", "B");                                  // Guava
4. ImmutableList.copyOf(Lists.newArrayList("A", "B", "C"));     // Guava

Empty immutable List

1. Collections.emptyList();
2. Collections.EMPTY_LIST;

List of Characters

1. Lists.charactersOf("String")                                 // Guava
2. Lists.newArrayList(Splitter.fixedLength(1).split("String"))  // Guava

List of Integers

Ints.asList(1,2,3);                                             // Guava

How to serve up a JSON response using Go?

Other users commenting that the Content-Type is plain/text when encoding. You have to set the Content-Type first w.Header().Set, then the HTTP response code w.WriteHeader.

If you call w.WriteHeader first then call w.Header().Set after you will get plain/text.

An example handler might look like this;

func SomeHandler(w http.ResponseWriter, r *http.Request) {
    data := SomeStruct{}
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(data)
}

String's Maximum length in Java - calling length() method

Considering the String class' length method returns an int, the maximum length that would be returned by the method would be Integer.MAX_VALUE, which is 2^31 - 1 (or approximately 2 billion.)

In terms of lengths and indexing of arrays, (such as char[], which is probably the way the internal data representation is implemented for Strings), Chapter 10: Arrays of The Java Language Specification, Java SE 7 Edition says the following:

The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

Furthermore, the indexing must be by int values, as mentioned in Section 10.4:

Arrays must be indexed by int values;

Therefore, it appears that the limit is indeed 2^31 - 1, as that is the maximum value for a nonnegative int value.

However, there probably are going to be other limitations, such as the maximum allocatable size for an array.

Java Programming: call an exe from Java and passing parameters

You're on the right track. The two constructors accept arguments, or you can specify them post-construction with ProcessBuilder#command(java.util.List) and ProcessBuilder#command(String...).

AngularJS - Attribute directive input value change

There's a great example in the AngularJS docs.

It's very well commented and should get you pointed in the right direction.

A simple example, maybe more so what you're looking for is below:

jsfiddle


HTML

<div ng-app="myDirective" ng-controller="x">
    <input type="text" ng-model="test" my-directive>
</div>

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngModel, function (v) {
                console.log('value changed, new value is: ' + v);
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}


Edit: Same thing, doesn't require ngModel jsfiddle:

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        scope: {
            myDirective: '='
        },
        link: function (scope, element, attrs) {
            // set the initial value of the textbox
            element.val(scope.myDirective);
            element.data('old-value', scope.myDirective);

            // detect outside changes and update our input
            scope.$watch('myDirective', function (val) {
                element.val(scope.myDirective);
            });

            // on blur, update the value in scope
            element.bind('propertychange keyup paste', function (blurEvent) {
                if (element.data('old-value') != element.val()) {
                    console.log('value changed, new value is: ' + element.val());
                    scope.$apply(function () {
                        scope.myDirective = element.val();
                        element.data('old-value', element.val());
                    });
                }
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Maybe it is simple, try this if you have a DataFrame. then make sure that both matrices or vectros that you're trying to combine have the same rows_name/index

I had the same issue. I changed the name indices of the rows to make them match each other here is an example for a matrix (principal component) and a vector(target) have the same row indicies (I circled them in the blue in the leftside of the pic)

Before, "when it was not working", I had the matrix with normal row indicies (0,1,2,3) while I had the vector with row indices (ID0, ID1, ID2, ID3) then I changed the vector's row indices to (0,1,2,3) and it worked for me.

enter image description here

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

<form action="portfolio.html">
 <button type="link" class="btn btn-primary btn-lg">View Work</button>
</form>

I just figured this out, and it links perfectly to another page without having my default link settings over ride my button classes! :)

Pass multiple values with onClick in HTML link

 $Name= "'".$row['Name']."'";
  $Val1= "'".$row['Val1']."'";
  $Year= "'".$row['Year']."'";
  $Month="'".$row['Month']."'";

 echo '<button type="button"   onclick="fun('.$Id.','.$Val1.','.$Year.','.$Month.','.$Id.');"  >submit</button>'; 

How to make the script wait/sleep in a simple way in unity

You were correct to use WaitForSeconds. But I suspect that you tried using it without coroutines. That's how it should work:

public void SomeMethod()
{
    StartCoroutine(SomeCoroutine());
}

private IEnumerator SomeCoroutine()
{
    TextUI.text = "Welcome to Number Wizard!";
    yield return new WaitForSeconds (3);
    TextUI.text = ("The highest number you can pick is " + max);
    yield return new WaitForSeconds (3);
    TextUI.text = ("The lowest number you can pick is " + min);
}

How to use terminal commands with Github?

git add myfile.h
git commit -m "your commit message"
git push -u origin master

if you don't remember all the files you need to update, use

git status

FFT in a single C-file

Your best bet is KissFFT - as its name implies it's simple, but it's still quite respectably fast, and a lot more lightweight than FFTW. It's also free, wheras FFTW requires a hefty licence fee if you want to include it in a commercial product.

Declaring variable workbook / Worksheet vba

Use Sheets rather than Sheet and activate them sequentially:

Sub kl()
    Dim wb As Workbook
    Dim ws As Worksheet
    Set wb = ActiveWorkbook
    Set ws = Sheets("Sheet1")
    wb.Activate
    ws.Select
End Sub

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

if else in a list comprehension

One way:

def change(f):
    if f is None:
        return unicode(f.strip())
    else:
        return ''

row = [change(x) for x in row]

Although then you have:

row = map(change, row)

Or you can use a lambda inline.

How to catch SQLServer timeout exceptions

To check for a timeout, I believe you check the value of ex.Number. If it is -2, then you have a timeout situation.

-2 is the error code for timeout, returned from DBNETLIB, the MDAC driver for SQL Server. This can be seen by downloading Reflector, and looking under System.Data.SqlClient.TdsEnums for TIMEOUT_EXPIRED.

Your code would read:

if (ex.Number == -2)
{
     //handle timeout
}

Code to demonstrate failure:

try
{
    SqlConnection sql = new SqlConnection(@"Network Library=DBMSSOCN;Data Source=YourServer,1433;Initial Catalog=YourDB;Integrated Security=SSPI;");
    sql.Open();

    SqlCommand cmd = sql.CreateCommand();
    cmd.CommandText = "DECLARE @i int WHILE EXISTS (SELECT 1 from sysobjects) BEGIN SELECT @i = 1 END";
    cmd.ExecuteNonQuery(); // This line will timeout.

    cmd.Dispose();
    sql.Close();
}
catch (SqlException ex)
{
    if (ex.Number == -2) {
        Console.WriteLine ("Timeout occurred");
    }
}

How to configure port for a Spring Boot application

Just have a application.properties in src/main/resources of the project and give there

server.port=****

where **** refers to the port number.

How do I make an HTTP request in Swift?

Here's a very simple Swift 4 example in a playground:

import UIKit
// run asynchronously in a playground
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

// create a url
let url = URL(string: "http://www.stackoverflow.com")

// create a data task
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
    if error != nil {
        print("there's a problem")
    }
    print(String(data: data!, encoding: String.Encoding.utf8) ?? "")
}

//running the task w/ resume
task.resume()

How to use if-else logic in Java 8 stream forEach

Just put the condition into the lambda itself, e.g.

animalMap.entrySet().stream()
        .forEach(
                pair -> {
                    if (pair.getValue() != null) {
                        myMap.put(pair.getKey(), pair.getValue());
                    } else {
                        myList.add(pair.getKey());
                    }
                }
        );

Of course, this assumes that both collections (myMap and myList) are declared and initialized prior to the above piece of code.


Update: using Map.forEach makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:

    animalMap.forEach(
            (key, value) -> {
                if (value != null) {
                    myMap.put(key, value);
                } else {
                    myList.add(key);
                }
            }
    );

Cassandra cqlsh - connection refused

I was experiencing the same issue with Cassandra 3.11.0, anytime I changed the address of rpc or listen address cqlsh wouldn't work. I had to add the same local ip to seeds

So after much trial and error my working cassandra.yml ended up like this:

class-name: org.apache.cassandra.locator.SimpleSeedProvider
parameters: 
    -seeds: "192.168.0.30"

listen_adress: 192.168.0.30
rpc_address: 192.168.0.30

VS 2017 Metadata file '.dll could not be found

Steps in Fixing this Error: MetaData File .dll could not be found.

  1. Clean All Projects.

  2. Unload All Projects.

  3. Reload All Projects.

  4. ReBuild Solution.

Then problem solved.

iOS how to set app icon and launch images

To save a bit time:

1) You can mark your app icon images all in finder and drag them into your Assets catalog all at once by dragging into one of the empty slots of the app icon imageset. When you hold your drag over the slot, several of the other slots look selected and when you drop those all will be filled up at once. Note that this works in XCode 8 (I haven't tried XCode 7), but in XCode 9 beta not yet.

Dragging into app icon Asset catalog imageset

2) The "Technical Q&A QA1686" apple documentation site has the sizes per app icon slot already calculated for you in a nice image and also contains the correct image names conventions.

App icon sizes

TempData keep() vs peek()

TempData is also a dictionary object that stays for the time of an HTTP Request. So, TempData can be used to maintain data between one controller action to the other controller action.

TempData is used to check the null values each time. TempData contain two method keep() and peek() for maintain data state from one controller action to others.

When TempDataDictionary object is read, At the end of request marks as deletion to current read object.

The keep() and peek() method is used to read the data without deletion the current read object.

You can use Peek() when you always want to hold/prevent the value for another request. You can use Keep() when prevent/hold the value depends on additional logic.

Overloading in TempData.Peek() & TempData.Keep() as given below.

TempData.Keep() have 2 overloaded methods.

  1. void keep() : That menace all the data not deleted on current request completion.

  2. void keep(string key) : persist the specific item in TempData with help of name.

TempData.Peek() no overloaded methods.

  1. object peek(string key) : return an object that contain items with specific key without making key for deletion.

Example for return type of TempData.Keep() & TempData.Peek() methods as given below.

public void Keep(string key) { _retainedKeys.Add(key); }

public object Peek(string key) { object value = values; return value; }

Rolling or sliding window iterator?

This is an old question but for those still interested there is a great implementation of a window slider using generators in this page (by Adrian Rosebrock).

It is an implementation for OpenCV however you can easily use it for any other purpose. For the eager ones i'll paste the code here but to understand it better I recommend visiting the original page.

def sliding_window(image, stepSize, windowSize):
    # slide a window across the image
    for y in xrange(0, image.shape[0], stepSize):
        for x in xrange(0, image.shape[1], stepSize):
            # yield the current window
            yield (x, y, image[y:y + windowSize[1], x:x + windowSize[0]])

Tip: You can check the .shape of the window when iterating the generator to discard those that do not meet your requirements

Cheers

Restricting JTextField input to Integers

When you type integer numbers to JtextField1 after key release it will go to inside try , for any other character it will throw NumberFormatException. If you set empty string to jTextField1 inside the catch so the user cannot type any other keys except positive numbers because JTextField1 will be cleared for each bad attempt.

 //Fields 
int x;
JTextField jTextField1;

 //Gui Code Here

private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {                                        
    try {
        x = Integer.parseInt(jTextField1.getText());
    } catch (NumberFormatException nfe) {
        jTextField1.setText("");
    }
}   

Why does the Visual Studio editor show dots in blank spaces?

Visual Studio is configured to show whitespace.

Press Ctrl+R, Ctrl+W.

If you are using C# keyboard mappings: (thanks Simeon)

Press Ctrl+E, S.

If you want to use the menu: (thanks angularsen)

Edit > Advanced > View White Space

In android app Toolbar.setTitle method has no effect – application name is shown as title

 public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       //custom toolbaar
       getSupportActionBar().setTitle("Abhijeet");

    }
}

Setting the selected value on a Django forms.ChoiceField

Both Tom and Burton's answers work for me eventually, but I had a little trouble figuring out how to apply them to a ModelChoiceField.

The only trick to it is that the choices are stored as tuples of (<model's ID>, <model's unicode repr>), so if you want to set the initial model selection, you pass the model's ID as the initial value, not the object itself or it's name or anything else. Then it's as simple as:

form = EmployeeForm(initial={'manager': manager_employee_id})

Alternatively the initial argument can be ignored in place of an extra line with:

form.fields['manager'].initial = manager_employee_id

Viewing contents of a .jar file

If I understand correctly, you want to see not only classes but also methods, properties and so on. The only tool I know that can do it is Eclipse - if you add a jar to project classpath, you would be able to browse its classes with methods and properties using usual package explorer.

Anyway, this is a good idea for a good standalone Java tool

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I solved this issue after changing the "Gradle Version" and "Android Plugin version".

You just goto "File>>Project Structure>>Project>>" and make changes here. I have worked a combination of versions from another working project of mine and added to the Project where I was getting this problem.

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

com.sun.mail.util.MailLogger is part of JavaMail API. It is already included in EE environment (that's why you can use it on your live server), but it is not included in SE environment.

Oracle docs:

The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.

99% that you run your tests in SE environment which means what you have to bother about adding it manually to your classpath when running tests.

If you're using maven add the following dependency (you might want to change version):

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.0</version>
</dependency>

Eloquent get only one column as an array

I came across this question and thought I would clarify that the lists() method of a eloquent builder object was depreciated in Laravel 5.2 and replaced with pluck().

// <= Laravel 5.1
Word_relation::where('word_one', $word_id)->lists('word_one')->toArray();
// >= Laravel 5.2
Word_relation::where('word_one', $word_id)->pluck('word_one')->toArray();

These methods can also be called on a Collection for example

// <= Laravel 5.1
  $collection = Word_relation::where('word_one', $word_id)->get();
  $array = $collection->lists('word_one');

// >= Laravel 5.2
  $collection = Word_relation::where('word_one', $word_id)->get();
  $array = $collection->pluck('word_one');

How can I mock an ES6 module import using Jest?

To mock an ES6 dependency module default export using Jest:

import myModule from '../myModule';
import dependency from '../dependency';

jest.mock('../dependency');

// If necessary, you can place a mock implementation like this:
dependency.mockImplementation(() => 42);

describe('myModule', () => {
  it('calls the dependency once with double the input', () => {
    myModule(2);

    expect(dependency).toHaveBeenCalledTimes(1);
    expect(dependency).toHaveBeenCalledWith(4);
  });
});

The other options didn't work for my case.

Show two digits after decimal point in c++

The easiest way to do this, is using cstdio's printf. Actually, i'm surprised that anyone mentioned printf! anyway, you need to include the library, like this...

#include<cstdio>

int main() {
    double total;
    cin>>total;
    printf("%.2f\n", total);
}

This will print the value of "total" (that's what %, and then ,total does) with 2 floating points (that's what .2f does). And the \n at the end, is just the end of line, and this works with UVa's judge online compiler options, that is:

g++ -lm -lcrypt -O2 -pipe -DONLINE_JUDGE filename.cpp

the code you are trying to run will not run with this compiler options...

Use success() or complete() in AJAX call

Is it that success() returns earlier than complete()?

Yes; the AJAX success() method runs before the complete() method.

Below is a diagram illustrating the process flow:

AJAX call process flow diagram.

It is important to note that

  • The success() (Local Event) is only called if the request was successful (no errors from the server, no errors with the data).

  • On the other hand, the complete() (Local Event) is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.

... more details on AJAX Events here.

Can't push image to Amazon ECR - fails with "no basic auth credentials"

aws ecr get-login --region us-west-1 --no-include-email

This command gives me correct command to login. If you dont use "--no-include-email",it will throw another error. Output of the above command looks like this docker login -u AWS -p **********************very big******. Copy that and execute it. Now it will show "Login Succeeded". Now you can push your image to ECR.

Make sure that your AMI rule has the permission for the user you tried to login.

How to round to 2 decimals with Python?

You can use the round function, which takes as its first argument the number and the second argument is the precision after the decimal point.

In your case, it would be:

answer = str(round(answer, 2))

How to set the project name/group/version, plus {source,target} compatibility in the same file?

Apparently this would be possible in settings.gradle with something like this.

rootProject.name = 'someName'
gradle.rootProject {
    it.sourceCompatibility = '1.7'
}

I recently received advice that a project property can be set by using a closure which will be called later when the Project is available.

Add (insert) a column between two columns in a data.frame

df <- data.frame(a=c(1,2), b=c(3,4), c=c(5,6))
df %>%
  mutate(d= a/2) %>%
  select(a, b, d, c)

results

  a b   d c
1 1 3 0.5 5
2 2 4 1.0 6

I suggest to use dplyr::select after dplyr::mutate. It has many helpers to select/de-select subset of columns.

In the context of this question the order by which you select will be reflected in the output data.frame.

Passing parameters in Javascript onClick event

This will work from JS without coupling to HTML:

document.getElementById("click-button").onclick = onClickFunction;

function onClickFunction()
{
    return functionWithArguments('You clicked the button!');
}

function functionWithArguments(text) {
    document.getElementById("some-div").innerText = text;
}

pycharm running way slow

In my case, it was very slow and i needed to change inspections settings, i tried everything, the only thing that worked was going from 2018.2 version to 2016.2, sometimes is better to be some updates behind...

How to get ID of clicked element with jQuery

Your IDs are #1, and cycle just wants a number passed to it. You need to remove the # before calling cycle.

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id');
    $container.cycle(id.replace('#', '')); 
    return false; 
});

Also, IDs shouldn't contain the # character, it's invalid (numeric IDs are also invalid). I suggest changing the ID to something like pager_1.

<a href="#" id="pager_1" class="pagerlink" >link</a>

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id');
    $container.cycle(id.replace('pager_', '')); 
    return false; 
});

Open an html page in default browser with VBA?

I find the most simple is

shell "explorer.exe URL"

This also works to open local folders.

php codeigniter count rows

Use this code:

$this->db->where(['id'=>2])->from("table name")->count_all_results();

or

$this->db->from("table name")->count_all_results();

Redirect HTTP to HTTPS on default virtual host without ServerName

Try adding this in your vhost config:

RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]

Twitter Bootstrap hide css class and jQuery

If an element has bootstrap's "hide" class and you want to display it with some sliding effect such as .slideDown(), you can cheat bootstrap like:

$('#hiddenElement').hide().removeClass('hide').slideDown('fast')

How to rename with prefix/suffix?

The easiest way to bulk rename files in directory is:

ls | xargs -I fileName mv fileName fileName.suffix

How can I combine two commits into one commit?

You want to git rebase -i to perform an interactive rebase.

If you're currently on your "commit 1", and the commit you want to merge, "commit 2", is the previous commit, you can run git rebase -i HEAD~2, which will spawn an editor listing all the commits the rebase will traverse. You should see two lines starting with "pick". To proceed with squashing, change the first word of the second line from "pick" to "squash". Then save your file, and quit. Git will squash your first commit into your second last commit.

Note that this process rewrites the history of your branch. If you are pushing your code somewhere, you'll have to git push -f and anybody sharing your code will have to jump through some hoops to pull your changes.

Note that if the two commits in question aren't the last two commits on the branch, the process will be slightly different.

Function pointer as parameter

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

How do I convert a dictionary to a JSON String in C#?

It seems a lot of different libraries and what not have seem to come and go over the previous years. However as of April 2016, this solution worked well for me. Strings easily replaced by ints.

TL/DR; Copy this if that's what you came here for:

    //outputfilename will be something like: "C:/MyFolder/MyFile.txt"
    void WriteDictionaryAsJson(Dictionary<string, List<string>> myDict, string outputfilename)
    {
        DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Dictionary<string, List<string>>));
        MemoryStream ms = new MemoryStream();
        js.WriteObject(ms, myDict); //Does the serialization.

        StreamWriter streamwriter = new StreamWriter(outputfilename);
        streamwriter.AutoFlush = true; // Without this, I've run into issues with the stream being "full"...this solves that problem.

        ms.Position = 0; //ms contains our data in json format, so let's start from the beginning
        StreamReader sr = new StreamReader(ms); //Read all of our memory
        streamwriter.WriteLine(sr.ReadToEnd()); // and write it out.

        ms.Close(); //Shutdown everything since we're done.
        streamwriter.Close();
        sr.Close();
    }

Two import points. First, be sure to add System.Runtime.Serliazation as a reference in your project inside Visual Studio's Solution Explorer. Second, add this line,

using System.Runtime.Serialization.Json;

at the top of the file with the rest of your usings, so the DataContractJsonSerializer class can be found. This blog post has more information on this method of serialization.

Data Format (Input / Output)

My data is a dictionary with 3 strings, each pointing to a list of strings. The lists of strings have lengths 3, 4, and 1. The data looks like this:

StringKeyofDictionary1 => ["abc","def","ghi"]
StringKeyofDictionary2 => ["String01","String02","String03","String04"]
Stringkey3 => ["someString"]

The output written to file will be on one line, here is the formatted output:

 [{
     "Key": "StringKeyofDictionary1",
     "Value": ["abc",
     "def",
     "ghi"]
 },
 {
     "Key": "StringKeyofDictionary2",
     "Value": ["String01",
     "String02",
     "String03",
     "String04",
 ]
 },
 {
     "Key": "Stringkey3",
     "Value": ["SomeString"]
 }]

Could not create the Java virtual machine

I had this issue today, and for me the problem was that I had allocated too much memory:

-Xmx1024M -XX:MaxPermSize=1024m

Once I reduced the PermGen space, everything worked fine:

-Xmx1024M -XX:MaxPermSize=512m

I know that doesn't look like much of a difference, but my machine only has 4GB of RAM, and apparently that was the straw that broke the camel's back. The Java VM was failing immediately upon every action because it was failing to allocate the memory.

Docker - a way to give access to a host USB or serial device?

If you would like to dynamically access USB devices which can be plugged in while the docker container is already running, for example access a just attached usb webcam at /dev/video0, you can add a cgroup rule when starting the container. This option does not need a --privileged container and only allows access to specific types of hardware.

Step 1

Check the device major number of the type of device you would like to add. You can look it up in the linux kernel documentation. Or you can check it for your device. For example to check the device major number for a webcam connected to /dev/video0, you can do a ls -la /dev/video0. This results in something like:

crw-rw----+ 1 root video 81, 0 Jul  6 10:22 /dev/video0

Where the first number (81) is the device major number. Some common device major numbers:

  • 81: usb webcams
  • 188: usb to serial converters

Step 2

Add rules when you start the docker container:

  • Add a --device-cgroup-rule='c major_number:* rmw' rule for every type of device you want access to
  • Add access to udev information so docker containers can get more info on your usb devices with -v /run/udev:/run/udev:ro
  • Map the /dev volume to your docker container with -v /dev:/dev

Wrap up

So to add all usb webcams and serial2usb devices to your docker container, do:

docker run -it -v /dev:/dev --device-cgroup-rule='c 188:* rmw' --device-cgroup-rule='c 81:* rmw' ubuntu bash

How to replace a string in a SQL Server Table Column

You can use this query

update table_name set column_name = replace (column_name , 'oldstring' ,'newstring') where column_name like 'oldstring%'

What value could I insert into a bit type column?

If you're using SQL Server, you can set the value of bit fields with 0 and 1

or

'true' and 'false' (yes, using strings)

...your_bit_field='false'... => equivalent to 0

Passing Parameters JavaFX FXML

You have to create one Context Class.

public class Context {
    private final static Context instance = new Context();
    public static Context getInstance() {
        return instance;
    }

    private Connection con;
    public void setConnection(Connection con)
    {
        this.con=con;
    }
    public Connection getConnection() {
        return con;
    }

    private TabRoughController tabRough;
    public void setTabRough(TabRoughController tabRough) {
        this.tabRough=tabRough;
    }

    public TabRoughController getTabRough() {
        return tabRough;
    }
}

You have to just set instance of controller in initialization using

Context.getInstance().setTabRough(this);

and you can use it from your whole application just using

TabRoughController cont=Context.getInstance().getTabRough();

Now you can pass parameter to any controller from whole application.

Make column fixed position in bootstrap

Use .col instead of col-lg-3 :

<div class="row">
   <div class="col">
      Fixed content
   </div>
   <div class="col-lg-9">
      Normal scrollable content
   </div>
</div>

How to make the web page height to fit screen height

Try:

#content{ background-color:#F3F3F3; margin:auto;width:70%;height:77%;}
#footer{width:100%;background-color:#666666;height:22%;}

(77% and 22% roughly preserves the proportions of content and footer and should not cause scrolling)

Post a json object to mvc controller with jquery and ajax

instead of receiving the json string a model binding is better. For example:

[HttpPost]       
public ActionResult AddUser(UserAddModel model)
{
    if (ModelState.IsValid) {
        return Json(new { Response = "Success" });
    }
    return Json(new { Response = "Error" });
}

<script>
function submitForm() {    
    $.ajax({
        type: 'POST',
        url: "@Url.Action("AddUser")",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: $("form[name=UserAddForm]").serialize(),
        success: function (data) {
            console.log(data);
        }
    });
}
</script>

Accessing bash command line args $@ vs $*

$*

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

$@

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Source: Bash man

Android textview usage as label and value

You can use <LinearLayout> to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use. Here is an example:

<LinearLayout
                    style="@style/FormItem"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                <TextView
                        style="@style/FormLabel"
                        android:layout_width="wrap_content"
                        android:layout_height="@dimen/default_element_height"
                        android:text="@string/name_label"
                        />

                <EditText
                        style="@style/FormText.Editable"
                        android:id="@+id/cardholderName"
                        android:layout_width="wrap_content"
                        android:layout_height="@dimen/default_element_height"
                        android:layout_weight="1"
                        android:gravity="right|center_vertical"
                        android:hint="@string/card_name_hint"
                        android:imeOptions="actionNext"
                        android:singleLine="true"
                        />
            </LinearLayout>

Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?

Update value of a nested dictionary of varying depth

The code below should solve the update({'k1': 1}, {'k1': {'k2': 2}}) issue in @Alex Martelli's answer the right way.

def deepupdate(original, update):
    """Recursively update a dict.

    Subdict's won't be overwritten but also updated.
    """
    if not isinstance(original, abc.Mapping):
        return update
    for key, value in update.items():
        if isinstance(value, abc.Mapping):
            original[key] = deepupdate(original.get(key, {}), value)
        else:
            original[key] = value
    return original

How to uninstall downloaded Xcode simulator?

Slightly off topic but could be very useful as it could be the basis for other tasks you might want to do with simulators.

I like to keep my simulator list to a minimum, and since there is no multi-select in the "Devices and Simulators" it is a pain to delete them all.

So I boot all the sims that I want to use then, remove all the simulators that I don't have booted.

Delete all the shutdown simulators:

xcrun simctl list | grep -w "Shutdown"  | grep -o "([-A-Z0-9]*)" | sed 's/[\(\)]//g' | xargs -I uuid xcrun simctl delete  uuid

If you need individual simulators back, just add them back to the list in "Devices and Simulators" with the plus button.

enter image description here

How to convert array to SimpleXML

Here's a function that did the trick for me:

Just call it with something like

echo arrayToXml("response",$arrayIWantToConvert);
function arrayToXml($thisNodeName,$input){
        if(is_numeric($thisNodeName))
            throw new Exception("cannot parse into xml. remainder :".print_r($input,true));
        if(!(is_array($input) || is_object($input))){
            return "<$thisNodeName>$input</$thisNodeName>";
        }
        else{
            $newNode="<$thisNodeName>";
            foreach($input as $key=>$value){
                if(is_numeric($key))
                    $key=substr($thisNodeName,0,strlen($thisNodeName)-1);
                $newNode.=arrayToXml3($key,$value);
            }
            $newNode.="</$thisNodeName>";
            return $newNode;
        }
    }

Can't connect to local MySQL server through socket homebrew

When you got the server running via

mysql.server start

you should see the socket in /tmp/mysql.sock. However, the system seems to expect it in /var/mysql/mysql.sock. To fix this, you have to create a symlink in /var/mysql:

sudo mkdir /var/mysql

sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

This solved it for me. Now my phpMyAdmin works happily with localhost and 127.0.0.1.

Credit goes to Henry

Best way to parse RSS/Atom feeds with PHP

The PHP RSS reader - http://www.scriptol.com/rss/rss-reader.php - is a complete but simple parser used by thousand of users...

How to get array keys in Javascript?

The stringified keys can be queried with Object.keys(array).

How do I escape double and single quotes in sed?

Regarding the single quote, see the code below used to replace the string let's with let us:

command:

echo "hello, let's go"|sed 's/let'"'"'s/let us/g'

result:

hello, let us go

jQuery multiple conditions within if statement

Try

if (!(i == 'InvKey' || i == 'PostDate')) {

or

if (i != 'InvKey' || i != 'PostDate') {

that says if i does not equals InvKey OR PostDate

How do I make JavaScript beep?

This will enable you to play the sound multiple times, in contrast to the top-voted answer:

var playSound = (function beep() {
    var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ3/6jYDAmxaiDG3/6xjQQCCKkRb/6kg/wW+kSJ5//rLobkLSiKmqP/0ikJuDaSaSf/6JiLYLEYnW/+kXg1WRVJL/9EmQ1YZIsv/6Qzwy5qk7/+tEU0nkls3/zIUMPKNX/6yZLf+kFgAfgGyLFAUwY//uQZAUABcd5UiNPVXAAAApAAAAAE0VZQKw9ISAAACgAAAAAVQIygIElVrFkBS+Jhi+EAuu+lKAkYUEIsmEAEoMeDmCETMvfSHTGkF5RWH7kz/ESHWPAq/kcCRhqBtMdokPdM7vil7RG98A2sc7zO6ZvTdM7pmOUAZTnJW+NXxqmd41dqJ6mLTXxrPpnV8avaIf5SvL7pndPvPpndJR9Kuu8fePvuiuhorgWjp7Mf/PRjxcFCPDkW31srioCExivv9lcwKEaHsf/7ow2Fl1T/9RkXgEhYElAoCLFtMArxwivDJJ+bR1HTKJdlEoTELCIqgEwVGSQ+hIm0NbK8WXcTEI0UPoa2NbG4y2K00JEWbZavJXkYaqo9CRHS55FcZTjKEk3NKoCYUnSQ0rWxrZbFKbKIhOKPZe1cJKzZSaQrIyULHDZmV5K4xySsDRKWOruanGtjLJXFEmwaIbDLX0hIPBUQPVFVkQkDoUNfSoDgQGKPekoxeGzA4DUvnn4bxzcZrtJyipKfPNy5w+9lnXwgqsiyHNeSVpemw4bWb9psYeq//uQZBoABQt4yMVxYAIAAAkQoAAAHvYpL5m6AAgAACXDAAAAD59jblTirQe9upFsmZbpMudy7Lz1X1DYsxOOSWpfPqNX2WqktK0DMvuGwlbNj44TleLPQ+Gsfb+GOWOKJoIrWb3cIMeeON6lz2umTqMXV8Mj30yWPpjoSa9ujK8SyeJP5y5mOW1D6hvLepeveEAEDo0mgCRClOEgANv3B9a6fikgUSu/DmAMATrGx7nng5p5iimPNZsfQLYB2sDLIkzRKZOHGAaUyDcpFBSLG9MCQALgAIgQs2YunOszLSAyQYPVC2YdGGeHD2dTdJk1pAHGAWDjnkcLKFymS3RQZTInzySoBwMG0QueC3gMsCEYxUqlrcxK6k1LQQcsmyYeQPdC2YfuGPASCBkcVMQQqpVJshui1tkXQJQV0OXGAZMXSOEEBRirXbVRQW7ugq7IM7rPWSZyDlM3IuNEkxzCOJ0ny2ThNkyRai1b6ev//3dzNGzNb//4uAvHT5sURcZCFcuKLhOFs8mLAAEAt4UWAAIABAAAAAB4qbHo0tIjVkUU//uQZAwABfSFz3ZqQAAAAAngwAAAE1HjMp2qAAAAACZDgAAAD5UkTE1UgZEUExqYynN1qZvqIOREEFmBcJQkwdxiFtw0qEOkGYfRDifBui9MQg4QAHAqWtAWHoCxu1Yf4VfWLPIM2mHDFsbQEVGwyqQoQcwnfHeIkNt9YnkiaS1oizycqJrx4KOQjahZxWbcZgztj2c49nKmkId44S71j0c8eV9yDK6uPRzx5X18eDvjvQ6yKo9ZSS6l//8elePK/Lf//IInrOF/FvDoADYAGBMGb7FtErm5MXMlmPAJQVgWta7Zx2go+8xJ0UiCb8LHHdftWyLJE0QIAIsI+UbXu67dZMjmgDGCGl1H+vpF4NSDckSIkk7Vd+sxEhBQMRU8j/12UIRhzSaUdQ+rQU5kGeFxm+hb1oh6pWWmv3uvmReDl0UnvtapVaIzo1jZbf/pD6ElLqSX+rUmOQNpJFa/r+sa4e/pBlAABoAAAAA3CUgShLdGIxsY7AUABPRrgCABdDuQ5GC7DqPQCgbbJUAoRSUj+NIEig0YfyWUho1VBBBA//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");  
    return function() {     
        snd.play(); 
    }
})();

playSound(); // Play first time
playSound(); // Play second time

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

I recommend not to use one of those methods as is. Write your own function which does the right thing.

MDN has given a good example on url encoding shown below.

var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);

console.log(header); 
// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"


function encodeRFC5987ValueChars (str) {
    return encodeURIComponent(str).
        // Note that although RFC3986 reserves "!", RFC5987 does not,
        // so we do not need to escape it
        replace(/['()]/g, escape). // i.e., %27 %28 %29
        replace(/\*/g, '%2A').
            // The following are not required for percent-encoding per RFC5987, 
            //  so we can allow for a little better readability over the wire: |`^
            replace(/%(?:7C|60|5E)/g, unescape);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Create instance of generic type whose constructor requires a parameter?

You can't use any parameterised constructor. You can use a parameterless constructor if you have a "where T : new()" constraint.

It's a pain, but such is life :(

This is one of the things I'd like to address with "static interfaces". You'd then be able to constrain T to include static methods, operators and constructors, and then call them.

Angular Directive refresh on parameter change

Link function only gets called once, so it would not directly do what you are expecting. You need to use angular $watch to watch a model variable.

This watch needs to be setup in the link function.

If you use isolated scope for directive then the scope would be

scope :{typeId:'@' }

In your link function then you add a watch like

link: function(scope, element, attrs) {
    scope.$watch("typeId",function(newValue,oldValue) {
        //This gets called when data changes.
    });
 }

If you are not using isolated scope use watch on some_prop

How do I make XAML DataGridColumns fill the entire DataGrid?

This will not expand the last column of the xaml grid to take the remaining space if AutoGeneratedColumns="True".

How to completely uninstall Android Studio on Mac?

I was also facing same kind of problem on my Macbook Pro. I took these very simple steps and freshly installed Android Studio.

** Link Contains Images, look if facing any problem.

These Very Simple Steps Can Solve Your Problem.

  1. Type "Command+option+Space Bar"
  2. Type "Android Studio"
  3. Click '+' button just below search box. image
  4. A new bar will come up "Kind" is "any" click on "kind" --> Others --> search for "system file" and select that by putting a tick mark.! And click on Ok. image
  5. Then select "are included" from the drop down menu !
  6. Then you get a lot of system file that need to be deleted to complete the fully un-installation of any app.
  7. Click "command+A" to select all files and take a look on the file remove is some video files are also included. And click "command + Delete"
  8. Empty your trash. Done

Search all the occurrences of a string in the entire project in Android Studio

TLDR: ??F on MacOS will open "Find in path" dialog.

First of all, this IDEA has a nice "Find Usages" command. It can be found in the context menu, when the cursor is on some field, method, etc.

It's context-aware, and as far as I know, is the best way to find class, method or field usage.

Alternatively, you can use the

Edit > Find > Find in path…

dialog, which allows you to search the whole workspace.

Also in IDEA 13 there is an awesome "Search Everywhere" option, by default called by double Shift. It allows you to search in project, files, classes, settings, and so on.

Also you can search from Project Structure dialog with "Find in Path…". Just call it by right mouse button on concrete directory and the search will be scoped, only inside that directory and it's sub-directory.

Enjoy!

How to have a default option in Angular.js select box

This working for me

ng-selected="true" 

PKIX path building failed in Java application

On Windows you can try these steps:

  1. Download a root CA certificate from the website.
  2. Find a file jssecacerts in the directory /lib/security with JRE (you can use a comand System.out.println(System.getProperty("java.home"); to find the folder with the current JRE). Make a backup of the file.
  3. Download a program portecle.
  4. Open the jssecacerts file in portecle.
  5. Enter the password: changeit.
  6. Import the downloaded certificate with porticle (Tools > Import Trusted Certificate).
  7. Click Save.
  8. Replace the original file jssecacerts.