Programs & Examples On #Open4

1067 error on attempt to start MySQL

Also check if all dirs which you wrote in the my.ini exists.

My problem was that tmpdir doeesn`t exist so MySQL daemon falls with error 1067.

[mysqld]
port= 3306
tmpdir = "C:/tmp"

In this case C:/tmp must exists.

How to do sed like text replace with python?

If you really want to use a sed command without installing a new Python module, you could simply do the following:

import subprocess
subprocess.call("sed command")

Android Paint: .measureText() vs .getTextBounds()

This is how I calculated the real dimensions for the first letter (you can change the method header to suit your needs, i.e. instead of char[] use String):

private void calculateTextSize(char[] text, PointF outSize) {
    // use measureText to calculate width
    float width = mPaint.measureText(text, 0, 1);

    // use height from getTextBounds()
    Rect textBounds = new Rect();
    mPaint.getTextBounds(text, 0, 1, textBounds);
    float height = textBounds.height();
    outSize.x = width;
    outSize.y = height;
}

Note that I'm using TextPaint instead of the original Paint class.

What is the difference between bool and Boolean types in C#

bool is a primitive type, meaning that the value (true/false in this case) is stored directly in the variable. Boolean is an object. A variable of type Boolean stores a reference to a Boolean object. The only real difference is storage. An object will always take up more memory than a primitive type, but in reality, changing all your Boolean values to bool isn't going to have any noticeable impact on memory usage.

I was wrong; that's how it works in java with boolean and Boolean. In C#, bool and Boolean are both reference types. Both of them store their value directly in the variable, both of them cannot be null, and both of them require a "convertTO" method to store their values in another type (such as int). It only matters which one you use if you need to call a static function defined within the Boolean class.

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

Updated 2018

IMO, the best way to approach this in Bootstrap 3 would be using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens. This way you keep the responsiveness...

@media (min-width:768px) {
  #sidebar {
      width: inherit;
      min-width: 240px;
      max-width: 240px;
      min-height: 100%;
      position:relative;
  }
  #sidebar2 {
      min-width: 160px;
      max-width: 160px;
      min-height: 100%;
      position:relative;
  }
  #main {
      width:calc(100% - 400px);
  }
}

Working Bootstrap Fixed-Fluid Demo

Bootstrap 4 will has flexbox so layouts like this will be much easier: http://www.codeply.com/go/eAYKvDkiGw

Ship an application with a database

If you are using ROOM there is a pretty straight forward path already https://developer.android.com/training/data-storage/room/prepopulate in the official documentation. Here's how it is in action to repopulate your database from an asset file:

Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db")
    .createFromAsset("database/myapp.db")
    .build()

or from a file:

Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db")
    .createFromFile(File("mypath"))
    .build()

and if you are not using Room, I strongly recommend you do

How to remove CocoaPods from a project?

$ sudo gem install cocoapods-deintegrate cocoapods-clean
$ pod deintegrate
$ pod clean
$ rm Podfile

No visible cause for "Unexpected token ILLEGAL"

This also could be happening if you're copying code from another document (like a PDF) into your console and trying to run it.

I was trying to run some example code out of a Javascript book I'm reading and was surprised it didn't run in the console.

Apparently, copying from the PDF introduces some unexpected, illegal, and invisible characters into the code.

How do you set autocommit in an SQL Server session?

I wanted a more permanent and quicker way. Because I tend to forget to add extra lines before writing my actual Update/Insert queries.

I did it by checking SET IMPLICIT_TRANSACTIONS check-box from Options. To navigate to Options Select Tools>Options>Query Execution>SQL Server>ANSI in your Microsoft SQL Server Management Studio.

Just make sure to execute commit or rollback after you are done executing your queries. Otherwise, the table you would have run the query will be locked for others.

What is the PostgreSQL equivalent for ISNULL()

How do I emulate the ISNULL() functionality ?

SELECT (Field IS NULL) FROM ...

Xpath: select div that contains class AND whose specific child element contains text

You can change your second condition to check only the span element:

...and contains(div/span, 'someText')]

If the span isn't always inside another div you can also use

...and contains(.//span, 'someText')]

This searches for the span anywhere inside the div.

The 'json' native gem requires installed build tools

I believe those installers make changes to the path. Did you try closing and re-opening the CMD window after running them and before the last attempt to install the gem that wants devkit present?

Also, be sure you are using the right devkit installer for your version of Ruby. The documentation at devkit wiki page has a requirements note saying:

For RubyInstaller versions 1.8.7, 1.9.2, and 1.9.3 use the DevKit 4.5.2

Why use prefixes on member variables in C++ classes

Others try to enforce using this->member whenever a member variable is used

That is usually because there is no prefix. The compiler needs enough information to resolve the variable in question, be it a unique name because of the prefix, or via the this keyword.

So, yes, I think prefixes are still useful. I, for one, would prefer to type '_' to access a member rather than 'this->'.

display:inline vs display:block

Block Elements: Elements liked div, p, headings are block level. They start from new line and occupy full width of parent element. Inline Elements: Elements liked b, i, span, img are inline level. They never start from new line and occupy width of content.

How to set text size of textview dynamically for different screens

EDIT: And As I Search on StackOverflow now I found This Question is Duplicate of : This and This

You need to use another function setTextSize(unit, size) with unit SP like this,

tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f);

Please read more for TypedValue constants.

Get file from project folder java

Just did a quick google search and found that

System.getProperty("user.dir");

returns the current working directory as String. So to get a File out of this, just use

File projectDir = new File(System.getProperty("user.dir"));

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

How do I get IntelliJ to recognize common Python modules?

This is how i solved my problem (i have imported the project and it was showing there only, newly created files were not showing those errors):

1) Command + alt + R (Control in case of windows

2) Debug window will appear, select your file and press right arrow (->) and choose Edit then press enter (Edit configuration setting window will appear)

3) Under configuration, at the bottom you can see the error (please select a module with a valid python sdk), So in Python Interpreter, check Use Specified Interpreter, then in drop down you select your Python version

(In case python is not there download python plugin for intelliJ using following link https://www.jetbrains.com/help/idea/2016.3/installing-updating-and-uninstalling-repository-plugins.html

4) Click on apply then close it.

Bingo it's done.

Use 'class' or 'typename' for template parameters?

There is a difference, and you should prefer class to typename.

But why?

typename is illegal for template template arguments, so to be consistent, you should use class:

template<template<class> typename MyTemplate, class Bar> class Foo { };    //  :(
template<template<class>    class MyTemplate, class Bar> class Foo { };    //  :)

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

IMO this link from Yochai Timmer was very good and relevant but painful to read. I wrote a summary.

Yochai, if you ever read this, please see the note at the end.


For the original post read : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs

Error

LINK : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs; use /NODEFAULTLIB:library

Meaning

one part of the system was compiled to use a single threaded standard (libc) library with debug information (libcd) which is statically linked

while another part of the system was compiled to use a multi-threaded standard library without debug information which resides in a DLL and uses dynamic linking

How to resolve

  • Ignore the warning, after all it is only a warning. However, your program now contains multiple instances of the same functions.

  • Use the linker option /NODEFAULTLIB:lib. This is not a complete solution, even if you can get your program to link this way you are ignoring a warning sign: the code has been compiled for different environments, some of your code may be compiled for a single threaded model while other code is multi-threaded.

  • [...] trawl through all your libraries and ensure they have the correct link settings

In the latter, as it in mentioned in the original post, two common problems can arise :

  • You have a third party library which is linked differently to your application.

  • You have other directives embedded in your code: normally this is the MFC. If any modules in your system link against MFC all your modules must nominally link against the same version of MFC.

For those cases, ensure you understand the problem and decide among the solutions.


Note : I wanted to include that summary of Yochai Timmer's link into his own answer but since some people have trouble to review edits properly I had to write it in a separate answer. Sorry

Submit form on pressing Enter with AngularJS

Angular supports this out of the box. Have you tried ngSubmit on your form element?

<form ng-submit="myFunc()" ng-controller="mycontroller">
   <input type="text" ng-model="name" />
    <br />
    <input type="text" ng-model="email" />
</form>

EDIT: Per the comment regarding the submit button, see Submitting a form by pressing enter without a submit button which gives the solution of:

<input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;"/>

If you don't like the hidden submit button solution, you'll need to bind a controller function to the Enter keypress or keyup event. This normally requires a custom directive, but the AngularUI library has a nice keypress solution set up already. See http://angular-ui.github.com/

After adding the angularUI lib, your code would be something like:

<form ui-keypress="{13:'myFunc($event)'}">
  ... input fields ...
</form>

or you can bind the enter keypress to each individual field.

Also, see this SO questions for creating a simple keypres directive: How can I detect onKeyUp in AngularJS?

EDIT (2014-08-28): At the time this answer was written, ng-keypress/ng-keyup/ng-keydown did not exist as native directives in AngularJS. In the comments below @darlan-alves has a pretty good solution with:

<input ng-keyup="$event.keyCode == 13 && myFunc()"... />

How to calculate a logistic sigmoid function in Python?

Here's how you would implement the logistic sigmoid in a numerically stable way (as described here):

def sigmoid(x):
    "Numerically-stable sigmoid function."
    if x >= 0:
        z = exp(-x)
        return 1 / (1 + z)
    else:
        z = exp(x)
        return z / (1 + z)

Or perhaps this is more accurate:

import numpy as np

def sigmoid(x):  
    return np.exp(-np.logaddexp(0, -x))

Internally, it implements the same condition as above, but then uses log1p.

In general, the multinomial logistic sigmoid is:

def nat_to_exp(q):
    max_q = max(0.0, np.max(q))
    rebased_q = q - max_q
    return np.exp(rebased_q - np.logaddexp(-max_q, np.logaddexp.reduce(rebased_q)))

(However, logaddexp.reduce could be more accurate.)

Chrome Extension: Make it run every page load

This code should do it:

manifest.json

   {
      "name": "Alert 'hello world!' on page opening",
      "version": "1.0",
      "manifest_version": 2,
      "content_scripts": [
        {
          "matches": [
            "<all_urls>"
          ],
          "js": ["content.js"]
        }
      ]
    }

content.js

alert('Hello world!')

Initializing a list to a known number of elements in Python

You could do this:

verts = list(xrange(1000))

That would give you a list of 1000 elements in size and which happens to be initialised with values from 0-999. As list does a __len__ first to size the new list it should be fairly efficient.

QString to char* conversion

the Correct Solution Would be like this

   QString k;
   k = "CRAZYYYQT";
   char ab[16];
   sprintf(ab,"%s",(const char *)((QByteArray)(k.toLatin1()).data()) );
   sprintf(ab,"%s",(const char *)((QByteArray)(k.toStdString()).data()));  
   sprintf(ab,"%s",(const char *)k.toStdString().c_str()  );
   qDebug()<<"--->"<<ab<<"<---";

if else condition in blade file (laravel 5.3)

No curly braces required you can directly write

@if($user->status =='waiting')         
      <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>         
@else
      <td>{{ $user->status }}</td>        
@endif

How do I append one string to another in Python?

it really depends on your application. If you're looping through hundreds of words and want to append them all into a list, .join() is better. But if you're putting together a long sentence, you're better off using +=.

Java Wait and Notify: IllegalMonitorStateException

You can't wait() on an object unless the current thread owns that object's monitor. To do that, you must synchronize on it:

class Runner implements Runnable
{
  public void run()
  {
    try
    {
      synchronized(Main.main) {
        Main.main.wait();
      }
    } catch (InterruptedException e) {}
    System.out.println("Runner away!");
  }
}

The same rule applies to notify()/notifyAll() as well.

The Javadocs for wait() mention this:

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws:

IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.

And from notify():

A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

C# Java HashMap equivalent

From C# equivalent to Java HashMap

I needed a Dictionary which accepted a "null" key, but there seems to be no native one, so I have written my own. It's very simple, actually. I inherited from Dictionary, added a private field to hold the value for the "null" key, then overwritten the indexer. It goes like this :

public class NullableDictionnary : Dictionary<string, string>
{
    string null_value;

    public StringDictionary this[string key]
    {
        get
        {
            if (key == null) 
            {
                return null_value;
            }
            return base[key];
        }
        set
        {
            if (key == null)
            {
                null_value = value;
            }
            else 
            {
                base[key] = value;
            }
        }
    }
}

Hope this helps someone in the future.

==========

I modified it to this format

public class NullableDictionnary : Dictionary<string, object>

How can I view a git log of just one user's commits?

You can even abbreviate this a bit by simply using part of the user name:

git log --author=mr  #if you're looking for mrfoobar's commits

How to convert ASCII code (0-255) to its corresponding character?

System.out.println((char)65); would print "A"

Computing cross-correlation function?

If you are looking for a rapid, normalized cross correlation in either one or two dimensions I would recommend the openCV library (see http://opencv.willowgarage.com/wiki/ http://opencv.org/). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results between -1 and 1).

While this is a C++ library the code is maintained with CMake and has python bindings so that access to the cross correlation functions is convenient. OpenCV also plays nicely with numpy. If I wanted to compute a 2-D cross-correlation starting from numpy arrays I could do it as follows.

import numpy
import cv

#Create a random template and place it in a larger image
templateNp = numpy.random.random( (100,100) )
image = numpy.random.random( (400,400) )
image[:100, :100] = templateNp

#create a numpy array for storing result
resultNp = numpy.zeros( (301, 301) )

#convert from numpy format to openCV format
templateCv = cv.fromarray(numpy.float32(template))
imageCv = cv.fromarray(numpy.float32(image))
resultCv =  cv.fromarray(numpy.float32(resultNp))

#perform cross correlation
cv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)

#convert result back to numpy array
resultNp = np.asarray(resultCv)

For just a 1-D cross-correlation create a 2-D array with shape equal to (N, 1 ). Though there is some extra code involved to convert to an openCV format the speed-up over scipy is quite impressive.

Get first day of week in PHP?

Try this:

function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y')
{
    $wk_ts  = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
    $mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
    return date($format, $mon_ts);
}

$sStartDate = week_start_date($week_number, $year);
$sEndDate   = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));

(from this forum thread)

Add x and y labels to a pandas plot

If you label the columns and index of your DataFrame, pandas will automatically supply appropriate labels:

import pandas as pd
values = [[1, 2], [2, 5]]
df = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                  index=['Index 1', 'Index 2'])
df.columns.name = 'Type'
df.index.name = 'Index'
df.plot(lw=2, colormap='jet', marker='.', markersize=10, 
        title='Video streaming dropout by category')

enter image description here

In this case, you'll still need to supply y-labels manually (e.g., via plt.ylabel as shown in the other answers).

How to install a python library manually

Here is the official FAQ on installing Python Modules: http://docs.python.org/install/index.html

There are some tips which might help you.

How to draw circle by canvas in Android?

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity 
{

     @Override
     public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
         setContentView(new MyView(this));
     }

     public class MyView extends View
     {
         Paint paint = null;
         public MyView(Context context) 
         {
              super(context);
              paint = new Paint();
         }

         @Override
         protected void onDraw(Canvas canvas) 
         {
            super.onDraw(canvas);
            int x = getWidth();
            int y = getHeight();
            int radius;
            radius = 100;
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.WHITE);
            canvas.drawPaint(paint);
            // Use Color.parseColor to define HTML colors
            paint.setColor(Color.parseColor("#CD5C5C"));
            canvas.drawCircle(x / 2, y / 2, radius, paint);
        }
     }
}

Edit if you want to draw circle at centre. You could also translate your entire canvas to center then draw circle at center.using

canvas.translate(getWidth()/2f,getHeight()/2f);
canvas.drawCircle(0,0, radius, paint);

These two link also help

http://www.compiletimeerror.com/2013/09/introduction-to-2d-drawing-in-android.html#.VIg_A5SSy9o

http://android-coding.blogspot.com/2012/04/draw-circle-on-canvas-canvasdrawcirclet.html

System.BadImageFormatException An attempt was made to load a program with an incorrect format

i have same problem what i did i just downloaded 32-bit dll and added it to my bin folder this is solved my problem

Map.Entry: How to use it?

Hash-Map stores the (key,value) pair as the Map.Entry Type.As you know that Hash-Map uses Linked Hash-Map(In case Collision occurs). Therefore each Node in the Bucket of Hash-Map is of Type Map.Entry. So whenever you iterate through the Hash-Map you will get Nodes of Type Map.Entry.

Now in your example when you are iterating through the Hash-Map, you will get Map.Entry Type(Which is Interface), To get the Key and Value from this Map.Entry Node Object, interface provided methods like getValue(), getKey() etc. So as per the code, In your Object you are adding all operators JButtons viz (+,-,/,*,=).

UITextField border color

borderColor on any view(or UIView Subclass) could also be set using storyboard with a little bit of coding and this approach could be really handy if you're setting border color on multiple UI Objects.

Below are the steps how to achieve it,

  1. Create a category on CALayer class. Declare a property of type UIColor with a suitable name, I'll name it as borderUIColor .
  2. Write the setter and getter for this property.
  3. In the 'Setter' method just set the "borderColor" property of layer to the new colors CGColor value.
  4. In the 'Getter' method return UIColor with layer's borderColor.

P.S: Remember, Categories can't have stored properties. 'borderUIColor' is used as a calculated property, just as a reference to achieve what we're focusing on.

Please have a look at the below code sample;

Objective C:

Interface File:

#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

@interface CALayer (BorderProperties)

// This assigns a CGColor to borderColor.
@property (nonatomic, assign) UIColor* borderUIColor;

@end

Implementation File:

#import "CALayer+BorderProperties.h"

@implementation CALayer (BorderProperties)

- (void)setBorderUIColor:(UIColor *)color {
    self.borderColor = color.CGColor;
}

- (UIColor *)borderUIColor {
    return [UIColor colorWithCGColor:self.borderColor];
}

@end

Swift 2.0:

extension CALayer {
var borderUIColor: UIColor {
    set {
        self.borderColor = newValue.CGColor
    }

    get {
        return UIColor(CGColor: self.borderColor!)
    }
}
}

And finally go to your storyboard/XIB, follow the remaining steps;

  1. Click on the View object for which you want to set border Color.
  2. Click on "Identity Inspector"(3rd from Left) in "Utility"(Right side of the screen) panel.
  3. Under "User Defined Runtime Attributes", click on the "+" button to add a key path.
  4. Set the type of the key path to "Color".
  5. Enter the value for key path as "layer.borderUIColor". [Remember this should be the variable name you declared in category, not borderColor here it's borderUIColor].
  6. Finally chose whatever color you want.

You've to set layer.borderWidth property value to at least 1 to see the border color.

Build and Run. Happy Coding. :)

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

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

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

Trust this certificate: [Yes]

changeit is the default truststore password

Get first day of week in SQL Server

For the basic (the current week's Sunday)

select cast(dateadd(day,-(datepart(dw,getdate())-1),getdate()) as date)

If previous week:

select cast(dateadd(day,-(datepart(dw,getdate())-1),getdate()) -7 as date)

Internally, we built a function that does it but if you need quick and dirty, this will do it.

Error:attempt to apply non-function

I got the error because of a clumsy typo:

This errors:

knitr::opts_chunk$seet(echo = FALSE)

Error: attempt to apply non-function

After correcting the typo, it works:

knitr::opts_chunk$set(echo = FALSE)

foreach loop in angularjs

Questions 1 & 2

So basically, first parameter is the object to iterate on. It can be an array or an object. If it is an object like this :

var values = {name: 'misko', gender: 'male'};

Angular will take each value one by one the first one is name, the second is gender.

If your object to iterate on is an array (also possible), like this :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]

Angular.forEach will take one by one starting by the first object, then the second object.

For each of this object, it will so take them one by one and execute a specific code for each value. This code is called the iterator function. forEach is smart and behave differently if you are using an array of a collection. Here is some exemple :

var obj = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(obj, function(value, key) {
  console.log(key + ': ' + value);
});
// it will log two iteration like this
// name: misko
// gender: male

So key is the string value of your key and value is ... the value. You can use the key to access your value like this : obj['name'] = 'John'

If this time you display an array, like this :

var values = [{ "Name" : "Thomas", "Password" : "thomasTheKing" },
           { "Name" : "Linda", "Password" : "lindatheQueen" }];
angular.forEach(values, function(value, key){
     console.log(key + ': ' + value);
});
// it will log two iteration like this
// 0: [object Object]
// 1: [object Object]

So then value is your object (collection), and key is the index of your array since :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]
// is equal to
{0: { "Name" : "Thomas", "Password" : "thomasTheKing" },
 1: { "Name" : "Linda", "Password" : "lindatheQueen" }}

I hope it answer your question. Here is a JSFiddle to run some code and test if you want : http://jsfiddle.net/ygahqdge/

Debugging your code

The problem seems to come from the fact $http.get() is an asynchronous request.

You send a query on your son, THEN when you browser end downloading it it execute success. BUT just after sending your request your perform a loop using angular.forEach without waiting the answer of your JSON.

You need to include the loop in the success function

var app = angular.module('testModule', [])
    .controller('testController', ['$scope', '$http', function($scope, $http){
    $http.get('Data/info.json').then(function(data){
         $scope.data = data;

         angular.forEach($scope.data, function(value, key){
         if(value.Password == "thomasTheKing")
           console.log("username is thomas");
         });
    });

});

This should work.

Going more deeply

The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

You can give a look at deferred/promise APIs, it is an important concept of Angular to make smooth asynchronous actions.

How to use 'git pull' from the command line?

One more option is to add the path of the privatekey file like this in terminal:

ssh-add "path to the privatekeyfile"

and then execute the pull command

Why don't self-closing script elements work?

XHTML 1 specification says:

?.3. Element Minimization and Empty Element Content

Given an empty instance of an element whose content model is not EMPTY (for example, an empty title or paragraph) do not use the minimized form (e.g. use <p> </p> and not <p />).

XHTML DTD specifies script elements as:

<!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>

How to determine an object's class?

You can use getSimpleName().

Let's say we have a object: Dog d = new Dog(),

The we can use below statement to get the class name: Dog. E.g.:

d.getClass().getSimpleName(); // return String 'Dog'.

PS: d.getClass() will give you the full name of your object.

jquery select element by xpath

document.evaluate() (DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved into a plugin in the current jQuery version, see https://plugins.jquery.com/xpath/). It simply converts XPath expressions into equivalent CSS selectors however.

How can I make a DateTimePicker display an empty string?

Better to use text box for calling/displaying date and while saving use DateTimePicker. Make visible property true or false as per requirement.

For eg : During form load make Load date in Textbox and make DTPIcker invisible and while adding vice versa

jquery, find next element by class

In this case you need to go up to the <tr> then use .next(), like this:

$(obj).closest('tr').next().find('.class');

Or if there may be rows in-between without the .class inside, you can use .nextAll(), like this:

$(obj).closest('tr').nextAll(':has(.class):first').find('.class');

AngularJS is rendering <br> as text not as a newline

I could be wrong because I've never used Angular, but I believe you are probably using ng-bind, which will create just a TextNode.

You will want to use ng-bind-html instead.

http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml

Update: It looks like you'll need to use ng-bind-html-unsafe='q.category'

http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe

Here's a demo:

http://jsfiddle.net/VFVMv/

Given two directory trees, how can I find out which files differ by content?

The command I use is:

diff -qr dir1/ dir2/

It is exactly the same as Mark's :) But his answer bothered me as it uses different types of flags, and it made me look twice. Using Mark's more verbose flags it would be:

diff  --brief --recursive dir1/ dir2/

I apologise for posting when the other answer is perfectly acceptable. Could not stop myself... working on being less pedantic.

TypeError: 'str' object cannot be interpreted as an integer

A simplest fix would be:

x = input("Give starting number: ")
y = input("Give ending number: ")

x = int(x)  # parse string into an integer
y = int(y)  # parse string into an integer

for i in range(x,y):
    print(i)

input returns you a string (raw_input in Python 2). int tries to parse it into an integer. This code will throw an exception if the string doesn't contain a valid integer string, so you'd probably want to refine it a bit using try/except statements.

Protect .NET code from reverse engineering?

Frankly, sometimes we need to obfuscate the code (for example, register license classes and so on). In this case, your project is not free. IMO, you should pay for a good obfucator.

Dotfuscator hides your code and .NET Reflector shows an error when you attempt to decompile it.

Visual Studio Code Automatic Imports

There is a Visual Studio Code issue you can track and thumbs up for this feature. There was also a User Voice issue, but I believe they moved voting to GitHub issues.

It seems they want auto import functionality in TypeScript, so it can be reused. TypeScript auto import issue to track and thumbs up here.

How to detect the swipe left or Right in Android?

the best answer is @Gal Rom 's. there is more information about it: touch event return's to child views first. and if you define onClick or onTouch listener for them, parnt view (for example fragment) will not receive any touch listener. So if you want define swipe listener for fragment in this situation, you must implement it in a new class:

    package com.neganet.QRelations.fragments;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.FrameLayout;

public class SwipeListenerFragment extends FrameLayout {
    private float x1,x2;
    static final int MIN_DISTANCE=150;
    private onSwipeEventDetected mSwipeDetectedListener;


    public SwipeListenerFragment(Context context) {
        super(context);
    }

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

    public SwipeListenerFragment(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean result=false;
        switch(ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                x1 = ev.getX();
                break;
            case MotionEvent.ACTION_UP:
                x2 = ev.getX();
                float deltaX = x2 - x1;
                if (Math.abs(deltaX) > MIN_DISTANCE)
                {
                    if(deltaX<0)
                    {
                        result=true;
                        if(mSwipeDetectedListener!=null)
                            mSwipeDetectedListener.swipeLeftDetected();

                    }else if(deltaX>0){
                        result=true;
                        if(mSwipeDetectedListener!=null)
                            mSwipeDetectedListener.swipeRightDetected();
                    }
                }
                break;
        }
        return result;
    }

    public interface onSwipeEventDetected
    {
        public void swipeLeftDetected();
        public void swipeRightDetected();

    }

    public void registerToSwipeEvents(onSwipeEventDetected listener)
    {
        this.mSwipeDetectedListener=listener;
    }
}

I changed @Gal Rom 's class. So it can detect both right and left swipe and specially it returns onInterceptTouchEvent true after detect. its important because if we dont do it some times child views maybe receive event and both of Swipe for fragment and onClick for child view (for example) runs and cause some issues. after making this class, you must change your fragment xml file:

    <com.neganet.QRelations.fragments.SwipeListenerFragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:id="@+id/main_list_layout"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_height="match_parent" tools:context="com.neganet.QRelations.fragments.mainList"
    android:background="@color/main_frag_back">

    <!-- TODO: Update blank fragment layout -->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/farazList"
        android:scrollbars="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="left|center_vertical" />
</com.neganet.QRelations.fragments.SwipeListenerFragment>

you see that begin tag is the class that we made. now in fragment class:

            View view=inflater.inflate(R.layout.fragment_main_list, container, false);
        SwipeListenerFragment tdView=(SwipeListenerFragment) view;
        tdView.registerToSwipeEvents(this);


and then Implement SwipeListenerFragment.onSwipeEventDetected in it:

        @Override
    public void swipeLeftDetected() {
        Toast.makeText(getActivity(), "left", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void swipeRightDetected() {
        Toast.makeText(getActivity(), "right", Toast.LENGTH_SHORT).show();
    }

It's a little complicated but works perfect :)

PHP Function Comments

You can get the comments of a particular method by using the ReflectionMethod class and calling ->getDocComment().

http://www.php.net/manual/en/reflectionclass.getdoccomment.php

How do I convert Int/Decimal to float in C#?

The same as an int:

float f = 6;

Also here's how to programmatically convert from an int to a float, and a single in C# is the same as a float:

int i = 8;
float f = Convert.ToSingle(i);

Or you can just cast an int to a float:

float f = (float)i;

Ansible: get current target host's IP address

http://docs.ansible.com/ansible/latest/plugins/lookup/dig.html

so in template, for e. g.:

{{ lookup('dig', ansible_host) }}

Notes:

  • Since not only DNS name could be used in inventory a check if it's not IP already better be added
  • Obviously enough this receipt wouldn't work as intended for indirect host specifications (like using jump hosts, for e. g.)

But still it serves 99 % (figuratively speaking) of use cases.

Why can't I make a vector of references?

yes you can, look for std::reference_wrapper, that mimics a reference but is assignable and also can be "reseated"

What is the best IDE for PHP?

  • Best of all: Notepad ++ (Free and helpful with colors and link)
  • Average: NetBeans (Normal IDE)
  • Not good: Eclipse (It crashes when you don't wait for it)
  • Oh and I forget: Don't ever use JDeveloper :D

Is Fortran easier to optimize than C for heavy calculations?

Any speed differences between Fortran and C will be more a function of compiler optimizations and the underlying math library used by the particular compiler. There is nothing intrinsic to Fortran that would make it faster than C.

Anyway, a good programmer can write Fortran in any language.

Remove specific characters from a string in Javascript

Simply replace it with nothing:

var string = 'F0123456'; // just an example
string.replace(/^F0+/i, ''); '123456'

How to compare strings in Bash

I have to disagree one of the comments in one point:

[ "$x" == "valid" ] && echo "valid" || echo "invalid"

No, that is not a crazy oneliner

It's just it looks like one to, hmm, the uninitiated...

It uses common patterns as a language, in a way;

And after you learned the language.

Actually, it's nice to read

It is a simple logical expression, with one special part: lazy evaluation of the logic operators.

[ "$x" == "valid" ] && echo "valid" || echo "invalid"

Each part is a logical expression; the first may be true or false, the other two are always true.

(
[ "$x" == "valid" ] 
&&
echo "valid"
)
||
echo "invalid"

Now, when it is evaluated, the first is checked. If it is false, than the second operand of the logic and && after it is not relevant. The first is not true, so it can not be the first and the second be true, anyway.
Now, in this case is the the first side of the logic or || false, but it could be true if the other side - the third part - is true.

So the third part will be evaluated - mainly writing the message as a side effect. (It has the result 0 for true, which we do not use here)

The other cases are similar, but simpler - and - I promise! are - can be - easy to read!
(I don't have one, but I think being a UNIX veteran with grey beard helps a lot with this.)

Trigger validation of all fields in Angular Form submit

I like the this approach in handling validation on button click.

  1. There is no need to invoke anything from controller,

  2. it's all handled with a directive.

on github

Copy file remotely with PowerShell

Simply use the administrative shares to copy files between systems. It's much easier this way.

Copy-Item -Path \\serverb\c$\programs\temp\test.txt -Destination \\servera\c$\programs\temp\test.txt;

By using UNC paths instead of local filesystem paths, you help to ensure that your script is executable from any client system with access to those UNC paths. If you use local filesystem paths, then you are cornering yourself into running the script on a specific computer.

This only works when a PowerShell session runs under the user who has rights to both administrative shares.

I suggest to use regular network share on server B with read-only access to everyone and simply call (from Server A):

Copy-Item -Path "\\\ServerB\SharedPathToSourceFile" -Destination "$Env:USERPROFILE" -Force -PassThru -Verbose

How to delete or add column in SQLITE?

DB Browser for SQLite allows you to add or drop columns.

In the main view, tab Database Structure, click on the table name. A button Modify Table gets enabled, which opens a new window where you can select the column/field and remove it.

Relative path in HTML

The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.

If the URL of your website is: http://www.example.com/mywebsite/ then starting at the root level starts above the "mywebsite" folder path.

CSS no text wrap

Use the css property overflow . For example:

  .item{
    width : 100px;
    overflow:hidden;
  }

The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.

I hope this helps.

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

What is the meaning of the prefix N in T-SQL statements and when should I use it?

Let me tell you an annoying thing that happened with the N' prefix - I wasn't able to fix it for two days.

My database collation is SQL_Latin1_General_CP1_CI_AS.

It has a table with a column called MyCol1. It is an Nvarchar

This query fails to match Exact Value That Exists.

SELECT TOP 1 * FROM myTable1 WHERE  MyCol1 = 'ESKI'  

// 0 result

using prefix N'' fixes it

SELECT TOP 1 * FROM myTable1 WHERE  MyCol1 = N'ESKI'  

// 1 result - found!!!!

Why? Because latin1_general doesn't have big dotted I that's why it fails I suppose.

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

I have faced the same problem when I was working with an Ant script to build my application.

I use Eclipse for my application development, and I changed the compiler version in build properties of the project. But that didn't work for me. Then I found out that I can provide the compiler version in the Ant script.

I modified the Ant script at the section where it compile Java files.

<target name="build-java" depends="prepare-build">
    <echo message="Compiling java files"/>
    <javac ....
           target="1.5"...
    </javac>
</target>

This worked for me to resolve the unsupported major minor issue.

Why and when to use angular.copy? (Deep Copy)

Use angular.copy when assigning value of object or array to another variable and that object value should not be changed.

Without deep copy or using angular.copy, changing value of property or adding any new property update all object referencing that same object.

_x000D_
_x000D_
var app = angular.module('copyExample', []);_x000D_
app.controller('ExampleController', ['$scope',_x000D_
  function($scope) {_x000D_
    $scope.printToConsole = function() {_x000D_
      $scope.main = {_x000D_
        first: 'first',_x000D_
        second: 'second'_x000D_
      };_x000D_
_x000D_
      $scope.child = angular.copy($scope.main);_x000D_
      console.log('Main object :');_x000D_
      console.log($scope.main);_x000D_
      console.log('Child object with angular.copy :');_x000D_
      console.log($scope.child);_x000D_
_x000D_
      $scope.child.first = 'last';_x000D_
      console.log('New Child object :')_x000D_
      console.log($scope.child);_x000D_
      console.log('Main object after child change and using angular.copy :');_x000D_
      console.log($scope.main);_x000D_
      console.log('Assing main object without copy and updating child');_x000D_
_x000D_
      $scope.child = $scope.main;_x000D_
      $scope.child.first = 'last';_x000D_
      console.log('Main object after update:');_x000D_
      console.log($scope.main);_x000D_
      console.log('Child object after update:');_x000D_
      console.log($scope.child);_x000D_
    }_x000D_
  }_x000D_
]);_x000D_
_x000D_
// Basic object assigning example_x000D_
_x000D_
var main = {_x000D_
  first: 'first',_x000D_
  second: 'second'_x000D_
};_x000D_
var one = main; // same as main_x000D_
var two = main; // same as main_x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same_x000D_
_x000D_
two = {_x000D_
  three: 'three'_x000D_
}; // two changed but one and main remains same_x000D_
console.log('main :' + JSON.stringify(main)); // one and main are same_x000D_
console.log('one :' + JSON.stringify(one)); // one and main are same_x000D_
console.log('two :' + JSON.stringify(two)); // two is changed_x000D_
_x000D_
two = main; // same as main_x000D_
_x000D_
two.first = 'last'; // change value of object's property so changed value of all object property _x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same with new value_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same with new value_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same with new value
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="copyExample" ng-controller="ExampleController">_x000D_
  <button ng-click='printToConsole()'>Explain</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Setting a property by reflection with a string value

Using Convert.ChangeType and getting the type to convert from the PropertyInfo.PropertyType.

propertyInfo.SetValue( ship,
                       Convert.ChangeType( value, propertyInfo.PropertyType ),
                       null );

Initialising an array of fixed size in python

>>> import numpy
>>> x = numpy.zeros((3,4))
>>> x
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> y = numpy.zeros(5)   
>>> y
array([ 0.,  0.,  0.,  0.,  0.])

x is a 2-d array, and y is a 1-d array. They are both initialized with zeros.

How do I call a SQL Server stored procedure from PowerShell?

Consider calling osql.exe (the command line tool for SQL Server) passing as parameter a text file written for each line with the call to the stored procedure.

SQL Server provides some assemblies that could be of use with the name SMO that have seamless integration with PowerShell. Here is an article on that.

http://www.databasejournal.com/features/mssql/article.php/3696731

There are API methods to execute stored procedures that I think are worth being investigated. Here a startup example:

http://www.eggheadcafe.com/software/aspnet/29974894/smo-running-a-stored-pro.aspx

What does IFormatProvider do?

The DateTimeFormatInfo class implements this interface, so it allows you to control the formatting of your DateTime strings.

How to get past the login page with Wget?

I directly gave cookies of an existing connection to wget with --no-cookies and the Cookie HTTP request header. In my case it was a Moodle university login where logging in looks more complex (using multiple requests with a login ticket). I added --post-data because it was a POST request.

For example, get all Moodle users list:

wget --no-cookies --header "Cookie: <name>=<value>" --post-data 'tab=search&name=+&personsubmit=Rechercher&keywords=&keywordsoption=allmine' https://moodle.unistra.fr/message/index.php

Error when testing on iOS simulator: Couldn't register with the bootstrap server

  1. Close simulator
  2. Stop the app from running in xCode.
  3. Open Activity Monitor and search for a process running with your App NAME.
  4. Kill this process in Activity Monitor
  5. Rebuild your project and you should be all set

How do you remove duplicates from a list whilst preserving order?

For no hashable types (e.g. list of lists), based on MizardX's:

def f7_noHash(seq)
    seen = set()
    return [ x for x in seq if str( x ) not in seen and not seen.add( str( x ) )]

IN vs OR in the SQL WHERE Clause

The best way to find out is looking at the Execution Plan.


I tried it with Oracle, and it was exactly the same.

CREATE TABLE performance_test AS ( SELECT * FROM dba_objects );

SELECT * FROM performance_test
WHERE object_name IN ('DBMS_STANDARD', 'DBMS_REGISTRY', 'DBMS_LOB' );

Even though the query uses IN, the Execution Plan says that it uses OR:

--------------------------------------------------------------------------------------    
| Id  | Operation         | Name             | Rows  | Bytes | Cost (%CPU)| Time     |    
--------------------------------------------------------------------------------------    
|   0 | SELECT STATEMENT  |                  |     8 |  1416 |   163   (2)| 00:00:02 |    
|*  1 |  TABLE ACCESS FULL| PERFORMANCE_TEST |     8 |  1416 |   163   (2)| 00:00:02 |    
--------------------------------------------------------------------------------------    

Predicate Information (identified by operation id):                                       
---------------------------------------------------                                       

   1 - filter("OBJECT_NAME"='DBMS_LOB' OR "OBJECT_NAME"='DBMS_REGISTRY' OR                
              "OBJECT_NAME"='DBMS_STANDARD')                                              

How to downgrade Node version

For windows:

Steps

  1. Go to Control panel> program and features>Node.js then uninstall

  2. Go to website: https://nodejs.org/en/ and download the version and install.

Simulate a button click in Jest

I needed to do a little bit of testing myself of a button component. These tests work for me ;-)

import { shallow } from "enzyme";
import * as React from "react";
import Button from "../button.component";

describe("Button Component Tests", () => {
    it("Renders correctly in DOM", () => {
        shallow(
            <Button text="Test" />
        );
    });
    it("Expects to find button HTML element in the DOM", () => {
        const wrapper = shallow(<Button text="test"/>)
        expect(wrapper.find('button')).toHaveLength(1);
    });

    it("Expects to find button HTML element with className test in the DOM", () => {
        const wrapper = shallow(<Button className="test" text="test"/>)
        expect(wrapper.find('button.test')).toHaveLength(1);
    });

    it("Expects to run onClick function when button is pressed in the DOM", () => {
        const mockCallBackClick = jest.fn();
        const wrapper = shallow(<Button onClick={mockCallBackClick} className="test" text="test"/>);
        wrapper.find('button').simulate('click');
        expect(mockCallBackClick.mock.calls.length).toEqual(1);
    });
});

How can I conditionally require form inputs with AngularJS?

In AngularJS (version 1.x), there is a build-in directive ngRequired

<input type='email'
       name='email'
       ng-model='user.email' 
       placeholder='[email protected]'
       ng-required='!user.phone' />

<input type='text'
       ng-model='user.phone'             
       placeholder='(xxx) xxx-xxxx'
       ng-required='!user.email' /> 

In Angular2 or above

<input type='email'
       name='email'
       [(ngModel)]='user.email' 
       placeholder='[email protected]'
       [required]='!user.phone' />

<input type='text'
       [(ngModel)]='user.phone'             
       placeholder='(xxx) xxx-xxxx'
       [required]='!user.email' /> 

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

I got the same error, I'm using laravel 5.4 with webpack, here package.json before:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    ...
    ...
  },
  "dependencies": {
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I had to move jquery and datatables.net npm packages under one of these "dependencies": {} or "devDependencies": {} in package.json and the error disappeared, after:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I hope that helps!

Delete the 'first' record from a table in SQL Server, without a WHERE condition

No, AFAIK, it's not possible to do it portably.

There's no defined "first" record anyway - on different SQL engines it's perfectly possible that "SELECT * FROM table" might return the results in a different order each time.

Converting Array to List

where stateb is List'' bucket is a two dimensional array

statesb= IntStream.of(bucket[j-1]).boxed().collect(Collectors.toList());

with import java.util.stream.IntStream;

see https://examples.javacodegeeks.com/core-java/java8-convert-array-list-example/

How to view the assembly behind the code using Visual C++?

For MSVC you can use the linker.

link.exe /dump /linenumbers /disasm /out:foo.dis foo.dll

foo.pdb needs to be available to get symbols

Add error bars to show standard deviation on a plot in R

In addition to @csgillespie's answer, segments is also vectorised to help with this sort of thing:

plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)

enter image description here

Export to CSV via PHP

Just like @Dampes8N said:

$result = mysql_query($sql,$conecction);
$fp = fopen('file.csv', 'w');
while($row = mysql_fetch_assoc($result)){
    fputcsv($fp, $row);
}
fclose($fp);

Hope this helps.

Javascript AES encryption

Use CryptoJS

Here's the code: https://github.com/odedhb/AES-encrypt

And here's an online working example: https://odedhb.github.io/AES-encrypt/

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I tried solving this problem for hours after I haven't used Android Studio some time and wasn't aware of the updates.

It is important that google() is the first item that stands in repositories like this:

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

Somehow google() was the second item after jcenter(), so everything was messed up and didn't work. Maybe this helps someone.

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

Avoid using Xcode to rename files in a folder reference. If you rename a file using Xcode, it will be marked for commit. If you later delete it before the commit, you will end up with this error.

Round double value to 2 decimal places

To remove the decimals from your double, take a look at this output

Obj C

double hellodouble = 10.025;
NSLog(@"Your value with 2 decimals: %.2f", hellodouble);
NSLog(@"Your value with no decimals: %.0f", hellodouble);

The output will be:

10.02 
10

Swift 2.1 and Xcode 7.2.1

let hellodouble:Double = 3.14159265358979
print(String(format:"Your value with 2 decimals: %.2f", hellodouble))
print(String(format:"Your value with no decimals: %.0f", hellodouble))

The output will be:

3.14 
3

Angular - ng: command not found

In my case

OS Version: Ubuntu 18.04.4 LTS

Node version v12.16.0

Remove ng from /usr/local/bin by using below command.

sudo rm -r ng

After that, installed ng by using command mentioned below.

sudo npm install -g @angular/cli

libpng warning: iCCP: known incorrect sRGB profile

Extending the friederbluemle solution, download the pngcrush and then use the code like this if you are running it on multiple png files

path =r"C:\\project\\project\\images" # path to all .png images
import os

png_files =[]

for dirpath, subdirs, files in os.walk(path):
    for x in files:
        if x.endswith(".png"):
            png_files.append(os.path.join(dirpath, x))

file =r'C:\\Users\\user\\Downloads\\pngcrush_1_8_9_w64.exe' #pngcrush file 


for name in png_files:
    cmd = r'{} -ow -rem allb -reduce {}'.format(file,name)
    os.system(cmd)

here all the png file related to projects are in 1 folder.

How do I bind a List<CustomObject> to a WPF DataGrid?

You should do it in the xaml code:

<DataGrid ItemsSource="{Binding list}" [...]>
  [...]
</DataGrid>

I would advise you to use an ObservableCollection as your backing collection, as that would propagate changes to the datagrid, as it implements INotifyCollectionChanged.

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";
    }
   }
  }
  }
 ?>

Run bash script from Windows PowerShell

There is now a "native" solution on Windows 10, after enabling Bash on Windows, you can enter Bash shell by typing bash: Bash on Windows

You can run Bash script like bash ./script.sh, but keep in mind that C drive is located at /mnt/c, and external hard drives are not mountable. So you might need to change your script a bit so it is compatible to Windows.

Also, even as root, you can still get permission denied when moving files around in /mnt, but you have your full root power in the / file system.

Also make sure your shell script is formatted with Unix style, or there can be errors. Example script

Maven fails to find local artifact

One of the errors I found around Maven is when I put my settings.xml file in the wrong directory. It has to be in .m2 folder under your user home dir. Check to make sure that is in the right place (along with settings-security.xml if you are using that).

load and execute order of scripts

The browser will execute the scripts in the order it finds them. If you call an external script, it will block the page until the script has been loaded and executed.

To test this fact:

// file: test.php
sleep(10);
die("alert('Done!');");

// HTML file:
<script type="text/javascript" src="test.php"></script>

Dynamically added scripts are executed as soon as they are appended to the document.

To test this fact:

<!DOCTYPE HTML>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <script type="text/javascript">
        var s = document.createElement('script');
        s.type = "text/javascript";
        s.src = "link.js"; // file contains alert("hello!");
        document.body.appendChild(s);
        alert("appended");
    </script>
    <script type="text/javascript">
        alert("final");
    </script>
</body>
</html>

Order of alerts is "appended" -> "hello!" -> "final"

If in a script you attempt to access an element that hasn't been reached yet (example: <script>do something with #blah</script><div id="blah"></div>) then you will get an error.

Overall, yes you can include external scripts and then access their functions and variables, but only if you exit the current <script> tag and start a new one.

How can I format bytes a cell in Excel as KB, MB, GB etc?

Here is one that I have been using: -

[<1000000]0.00," KB";[<1000000000]0.00,," MB";0.00,,," GB"

Seems to work fine.

How to step through Python code to help debug issues?

If you want an IDE with integrated debugger, try PyScripter.

Extract month and year from a zoo::yearmon object

For large vectors:

y = as.POSIXlt(date1)$year + 1900    # x$year : years since 1900
m = as.POSIXlt(date1)$mon + 1        # x$mon : 0–11

how to draw smooth curve through N points using javascript HTML5 canvas?

This code is perfect for me:

this.context.beginPath();
this.context.moveTo(data[0].x, data[0].y);
for (let i = 1; i < data.length; i++) {
  this.context.bezierCurveTo(
    data[i - 1].x + (data[i].x - data[i - 1].x) / 2,
    data[i - 1].y,
    data[i - 1].x + (data[i].x - data[i - 1].x) / 2,
    data[i].y,
    data[i].x,
    data[i].y);
}

you have correct smooth line and correct endPoints NOTICE! (y = "canvas height" - y);

Javascript loop through object array?

To reference the contents of the single array containing one or more objects i.e. everything in the brackets of something like this {messages: [{"a":1,"b":2}] } ,just add [0] to the query to get the first array element

e.g. messages[0] will reference the object {"a":1,"b":2} as opposed to just messages which would reference the entire array [{"a":1,"b":2}]

from there you can work with the result as typical object and use Object.keys for example to get "a" and "b".

How to delete from a text file, all lines that contain a specific string?

There are many other ways to delete lines with specific string besides sed:

AWK

awk '!/pattern/' file > temp && mv temp file

Ruby (1.9+)

ruby -i.bak -ne 'print if not /test/' file

Perl

perl -ni.bak -e "print unless /pattern/" file

Shell (bash 3.2 and later)

while read -r line
do
  [[ ! $line =~ pattern ]] && echo "$line"
done <file > o
mv o file

GNU grep

grep -v "pattern" file > temp && mv temp file

And of course sed (printing the inverse is faster than actual deletion):

sed -n '/pattern/!p' file

How to change context root of a dynamic web project in Eclipse?

After changing the context root in project properties you have to remove your web application from Tomcat (using Add and Remove... on the context menu of the server), redeploy, then re-add your application and redeploy. It worked for me.

If you are struck you have another choice: select the Tomcat server in the Servers view. Double clicking on that server (or selecting Open in the context menu) brings a multipage editor where there is a Modules page. Here you can change the root context of your module (called Path on this page).

Import Android volley to Android Studio

Add this in your "build.gradle" of you app.

implementation 'com.android.volley:volley:1.1.1'

Website screenshots

Since PHP 5.2.2 it is possible, to capture a website with PHP solely!

imagegrabscreen — Captures the whole screen

<?php
$img = imagegrabscreen();
imagepng($img, 'screenshot.png');
?>

imagegrabwindow - Grabs a window or its client area using a windows handle (HWND property in COM instance)

<?php
$Browser = new COM('InternetExplorer.Application');
$Browserhandle = $Browser->HWND;
$Browser->Visible = true;
$Browser->Fullscreen = true;
$Browser->Navigate('http://www.stackoverflow.com');

while($Browser->Busy){
  com_message_pump(4000);
}

$img = imagegrabwindow($Browserhandle, 0);
$Browser->Quit();
imagepng($img, 'screenshot.png');
?>

Edit: Note, these functions are available on Windows systems ONLY!

Can I send a ctrl-C (SIGINT) to an application on Windows?

The closest that I've come to a solution is the SendSignal 3rd party app. The author lists source code and an executable. I've verified that it works under 64-bit windows (running as a 32-bit program, killing another 32-bit program), but I've not figured out how to embed the code into a windows program (either 32-bit or 64-bit).

How it works:

After much digging around in the debugger I discovered that the entry point that actually does the behavior associated with a signal like ctrl-break is kernel32!CtrlRoutine. The function had the same prototype as ThreadProc, so it can be used with CreateRemoteThread directly, without having to inject code. However, that's not an exported symbol! It's at different addresses (and even has different names) on different versions of Windows. What to do?

Here is the solution I finally came up with. I install a console ctrl handler for my app, then generate a ctrl-break signal for my app. When my handler gets called, I look back at the top of the stack to find out the parameters passed to kernel32!BaseThreadStart. I grab the first param, which is the desired start address of the thread, which is the address of kernel32!CtrlRoutine. Then I return from my handler, indicating that I have handled the signal and my app should not be terminated. Back in the main thread, I wait until the address of kernel32!CtrlRoutine has been retrieved. Once I've got it, I create a remote thread in the target process with the discovered start address. This causes the ctrl handlers in the target process to be evaluated as if ctrl-break had been pressed!

The nice thing is that only the target process is affected, and any process (even a windowed process) can be targeted. One downside is that my little app can't be used in a batch file, since it will kill it when it sends the ctrl-break event in order to discover the address of kernel32!CtrlRoutine.

(Precede it with start if running it in a batch file.)

Datagrid binding in WPF

Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
    <DataGrid.Columns>                
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

jQuery form input select by id

You can do that using the descendant selectors:

 $("#a #b")

However, id values are supposed to be unique on a page.

How to Convert string "07:35" (HH:MM) to TimeSpan

You can convert the time using the following code.

TimeSpan _time = TimeSpan.Parse("07:35");

But if you want to get the current time of the day you can use the following code:

TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;

The result will be:

03:54:35.7763461

With a object cantain the Hours, Minutes, Seconds, Ticks and etc.

how to get the value of a textarea in jquery?

You don't need to use textarea#message

var message = $('textarea#message').val();

You can directly use

var message = $('#message').val();

How to print Unicode character in C++?

I needed to show the string in UI as well as save that to an xml configuration file. The above specified format is good for string in c++, I would add we can have the xml compatible string for the special character by replacing "\u" by "&#x" and adding a ";" at the end.

For example : C++ : "\u0444" --> XML : "&#x0444;"

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

I have to report another possibility, after ALL the previous ones:

I got "cannot open git-upload-pack" during eclipse GIT pull operation (through a proxy tunnel), so I have to try an access via browser to the same GIT URL, eventually authenticating correctly in the proxy, and only after via eclipse is possible to make the pull from GIT without any error. Hope useful.

Repeat a string in JavaScript a number of times

In ES2015/ES6 you can use "*".repeat(n)

So just add this to your projects, and your are good to go.

  String.prototype.repeat = String.prototype.repeat || 
    function(n) {
      if (n < 0) throw new RangeError("invalid count value");
      if (n == 0) return "";
      return new Array(n + 1).join(this.toString()) 
    };

Codesign error: Provisioning profile cannot be found after deleting expired profile

I just encountered this problem in my Xcode 4. To fix it, you need to put all the correct provisions into both Debug and Release config.

I was trying to submit (by archiving) my app. So I just change the Debug provisions to "Don't Code Sign", and the Release provision to my app's appstore provision.

This fix it and enables me to archive normally. Hope that helps.

C++ Singleton design pattern

Simple singleton class, This must be your header class file

#ifndef SC_SINGLETON_CLASS_H
#define SC_SINGLETON_CLASS_H

class SingletonClass
{
    public:
        static SingletonClass* Instance()
        {
           static SingletonClass* instance = new SingletonClass();
           return instance;
        }

        void Relocate(int X, int Y, int Z);

    private:
        SingletonClass();
        ~SingletonClass();
};

#define sSingletonClass SingletonClass::Instance()

#endif

Access your singleton like this:

sSingletonClass->Relocate(1, 2, 5);

Using grep to help subset a data frame in R

It's pretty straightforward using [ to extract:

grep will give you the position in which it matched your search pattern (unless you use value = TRUE).

grep("^G45", My.Data$x)
# [1] 2

Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with [ (where you would use My.Data[rows, cols] to get specific rows and columns).

My.Data[grep("^G45", My.Data$x), ]
#      x y
# 2 G459 2

The help-page for subset shows how you can use grep and grepl with subset if you prefer using this function over [. Here's an example.

subset(My.Data, grepl("^G45", My.Data$x))
#      x y
# 2 G459 2

As of R 3.3, there's now also the startsWith function, which you can again use with subset (or with any of the other approaches above). According to the help page for the function, it's considerably faster than using substring or grepl.

subset(My.Data, startsWith(as.character(x), "G45"))
#      x y
# 2 G459 2

Email Address Validation in Android on EditText

public static boolean isEmailValid(String email) {
    boolean isValid = false;

    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    CharSequence inputStr = email;

    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.matches()) {
        isValid = true;
    }
    return isValid;
}

SQL multiple columns in IN clause

It often ends up being easier to load your data into the database, even if it is only to run a quick query. Hard-coded data seems quick to enter, but it quickly becomes a pain if you start having to make changes.

However, if you want to code the names directly into your query, here is a cleaner way to do it:

with names (fname,lname) as (
    values
        ('John','Smith'),
        ('Mary','Jones')
)
select city from user
    inner join names on
        fname=firstName and
        lname=lastName;

The advantage of this is that it separates your data out of the query somewhat.

(This is DB2 syntax; it may need a bit of tweaking on your system).

SQL SELECT everything after a certain character

I've been working on something similar and after a few tries and fails came up with this:

Example: STRING-TO-TEST-ON = 'ab,cd,ef,gh'

I wanted to extract everything after the last occurrence of "," (comma) from the string... resulting in "gh".

My query is:

SELECT SUBSTR('ab,cd,ef,gh' FROM (LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1)) AS `wantedString`

Now let me try and explain what I did ...

  1. I had to find the position of the last "," from the string and to calculate the wantedString length, using LOCATE(",",REVERSE('ab,cd,ef,gh'))-1 by reversing the initial string I actually had to find the first occurrence of the "," in the string ... which wasn't hard to do ... and then -1 to actually find the string length without the ",".

  2. calculate the position of my wantedString by subtracting the string length I've calculated at 1st step from the initial string length:

    LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1

I have (+1) because I actually need the string position after the last "," .. and not containing the ",". Hope it makes sense.

  1. all it remain to do is running a SUBSTR on my initial string FROM the calculated position.

I haven't tested the query on large strings so I do not know how slow it is. So if someone actually tests it on a large string I would very happy to know the results.

Swing JLabel text change on the running application

Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:

jLabel.setText("new Value");

A simple demo code will be:

    JFrame frame = new JFrame("Demo");
    frame.setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(250,100);

    final JLabel label = new JLabel("flag");
    JButton button = new JButton("Change flag");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            label.setText("new value");
        }
    });

    frame.add(label, BorderLayout.NORTH);
    frame.add(button, BorderLayout.CENTER);
    frame.setVisible(true);

Why is this program erroneously rejected by three C++ compilers?

Run the compiler through OCR. It might solve the compatibility issue.

How to iterate through XML in Powershell?

PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

Or shorter

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
  % {$_.Node.'#text'}

PHP: Count a stdClass object

There is nothing wrong with count() here, "trends" is the only key that is being counted in this case, you can try doing:

count($obj->trends);

Or:

count($obj->trends['2009-08-21 11:05']);

Or maybe even doing:

count($obj, COUNT_RECURSIVE);

How to use Sublime over SSH

A solution that worked great for me - edit locally on Mac, and have the file automatically synchronized to a remote machine

  1. Make sure you have passwordless login to the remote machine. If not, follow these steps http://osxdaily.com/2012/05/25/how-to-set-up-a-password-less-ssh-login/

  2. create a file in ~/Library/LaunchAgents/filesynchronizer.plist, with the following content:

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>filesynchronizer</string> <key>ProgramArguments</key> <array> <string>/usr/bin/rsync</string> <string>-avz</string> <string>/Users/USERNAME/SyncDirectory</string> <string>USERNAME@REMOTEMACHINE:~</string> </array> <key>WatchPaths</key> <array> <string>/Users/USERNAME/SyncDirectory</string> </array> </dict> </plist>

  3. In a terminal window run

    launchctl load ~/Library/LaunchAgents/filesynchronizer.plist

  4. That's it. Any changes to any files in ~/SyncDirectory will be synchronized to ~/SyncDirectory on the remote machine. Local changes will override any remote changes.

This creates a launchd job that monitors SyncDirectory, and whenever anything changes there runs rsync to synchronize the directory to the remote machine.

find vs find_by vs where

Edit: This answer is very old and other, better answers have come up since this post was made. I'd advise looking at the one posted below by @Hossam Khamis for more details.

Use whichever one you feel suits your needs best.

The find method is usually used to retrieve a row by ID:

Model.find(1)

It's worth noting that find will throw an exception if the item is not found by the attribute that you supply. Use where (as described below, which will return an empty array if the attribute is not found) to avoid an exception being thrown.

Other uses of find are usually replaced with things like this:

Model.all
Model.first

find_by is used as a helper when you're searching for information within a column, and it maps to such with naming conventions. For instance, if you have a column named name in your database, you'd use the following syntax:

Model.find_by(name: "Bob")

.where is more of a catch all that lets you use a bit more complex logic for when the conventional helpers won't do, and it returns an array of items that match your conditions (or an empty array otherwise).

Spring Boot: How can I set the logging level with application.properties?

You can try setting the log level to DEBUG it will show everything while starting the application

logging.level.root=DEBUG

How to use RANK() in SQL Server

To answer your question title, "How to use Rank() in SQL Server," this is how it works:

I will use this set of data as an example:

create table #tmp
(
  column1 varchar(3),
  column2 varchar(5),
  column3 datetime,
  column4 int
)

insert into #tmp values ('AAA', 'SKA', '2013-02-01 00:00:00', 10)
insert into #tmp values ('AAA', 'SKA', '2013-01-31 00:00:00', 15)
insert into #tmp values ('AAA', 'SKB', '2013-01-31 00:00:00', 20)
insert into #tmp values ('AAA', 'SKB', '2013-01-15 00:00:00', 5)
insert into #tmp values ('AAA', 'SKC', '2013-02-01 00:00:00', 25)

You have a partition which basically specifies grouping.

In this example, if you partition by column2, the rank function will create ranks for groups of column2 values. There will be different ranks for rows where column2 = 'SKA' than rows where column2 = 'SKB' and so on.

The ranks are decided like this: The rank for every record is one plus the number of ranks that come before it in its partition. The rank will only increment when one of the fields you selected (other than the partitioned field(s)) is different than the ones that come before it. If all of the selected fields are the same, then the ranks will tie and both will be assigned the value, one.

Knowing this, if we only wanted to select one value from each group in column two, we could use this query:

with cte as 
(
  select *, 
  rank() over (partition by column2 
             order by column3) rnk
  from t

) select * from cte where rnk = 1 order by column3;

Result:

COLUMN1 | COLUMN2   | COLUMN3                           |COLUMN4 | RNK
------------------------------------------------------------------------------
AAA     | SKB   | January, 15 2013 00:00:00+0000    |5   | 1
AAA     | SKA   | January, 31 2013 00:00:00+0000    |15  | 1
AAA     | SKC   | February, 01 2013 00:00:00+0000   |25  | 1

SQL DEMO

XPath query to get nth instance of an element

This seems to work:

/descendant::input[@id="search_query"][2]

I go this from "XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition" by Michael Kay.

There is also a note in the "Abbreviated Syntax" section of the XML Path Language specification http://www.w3.org/TR/xpath/#path-abbrev that provided a clue.

How to get current working directory using vba?

Your code: path = ActiveWorkbook.Path

returns blank because you haven't saved your workbook yet.

To overcome your problem, go back to the Excel sheet, save your sheet, and run your code again.

This time it will not show blank, but will show you the path where it is located (current folder)

I hope that helped.

Run on server option not appearing in Eclipse

Right click on the project, go to "Run as", select "Run configurations" and create a run configuration.

ASP.NET Setting width of DataBound column in GridView

Width can be set to specific column as below: By percentages:

<asp:BoundField HeaderText="UserInfo"  DataField="UserInfo"  
SortExpression="UserInfo" ItemStyle-Width="100%"></asp:BoundField>

OR

By pixel:

<asp:BoundField HeaderText="UserInfo"  DataField="UserInfo"  
SortExpression="UserInfo" ItemStyle-Width="500px"></asp:BoundField>

jQuery-UI datepicker default date

If you want to update the highlighted day to a different day based on some server time, you can override the Date Picker code to allow for a new custom option named localToday or whatever you'd like to name it.

A small tweak to the selected answer in jQuery UI DatePicker change highlighted "today" date

// Get users 'today' date
var localToday = new Date();
localToday.setDate(tomorrow.getDate()+1); // tomorrow

// Pass the today date to datepicker
$( "#datepicker" ).datepicker({
    showButtonPanel: true,
    localToday: localToday    // This option determines the highlighted today date
});

I've overridden 2 datepicker methods to conditionally use a new setting for the "today" date instead of a new Date(). The new setting is called localToday.

Override $.datepicker._gotoToday and $.datepicker._generateHTML like this:

$.datepicker._gotoToday = function(id) {
    /* ... */
    var date = inst.settings.localToday || new Date()
    /* ... */
}

$.datepicker._generateHTML = function(inst) {
    /* ... */
    tempDate = inst.settings.localToday || new Date()
    /* ... */
}

Here's a demo which shows the full code and usage: http://jsfiddle.net/NAzz7/5/

Filter df when values matches part of a string in pyspark

When filtering a DataFrame with string values, I find that the pyspark.sql.functions lower and upper come in handy, if your data could have column entries like "foo" and "Foo":

import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))

Memory address of an object in C#

Instead of this code, you should call GetHashCode(), which will return a (hopefully-)unique value for each instance.

You can also use the ObjectIDGenerator class, which is guaranteed to be unique.

Setting Spring Profile variable

For Tomcat 8:

Linux :

Create setenv.sh and update it with following:

export SPRING_PROFILES_ACTIVE=dev

Windows:

Create setenv.bat and update it with following:

set SPRING_PROFILES_ACTIVE=dev

PHP function to get the subdomain of a URL

From PHP 5.3 you can use strstr() with true parameter

echo strstr($_SERVER["HTTP_HOST"], '.', true); //prints en

What do two question marks together mean in C#?

It's the null coalescing operator.

http://msdn.microsoft.com/en-us/library/ms173224.aspx

Yes, nearly impossible to search for unless you know what it's called! :-)

EDIT: And this is a cool feature from another question. You can chain them.

Hidden Features of C#?

how to change directory using Windows command line

Another alternative is pushd, which will automatically switch drives as needed. It also allows you to return to the previous directory via popd:

C:\Temp>pushd D:\some\folder
D:\some\folder>popd
C:\Temp>_

Spring Data JPA map the native query result to Non-Entity POJO

I think the easiest way to do that is to use so called projection. It can map query results to interfaces. Using SqlResultSetMapping is inconvienient and makes your code ugly :).

An example right from spring data JPA source code:

public interface UserRepository extends JpaRepository<User, Integer> {

   @Query(value = "SELECT firstname, lastname FROM SD_User WHERE id = ?1", nativeQuery = true)
   NameOnly findByNativeQuery(Integer id);

   public static interface NameOnly {

     String getFirstname();

     String getLastname();

  }
}

You can also use this method to get a list of projections.

Check out this spring data JPA docs entry for more info about projections.

Note 1:

Remember to have your User entity defined as normal - the fields from projected interface must match fields in this entity. Otherwise field mapping might be broken (getFirstname() might return value of last name et cetera).

Note 2:

If you use SELECT table.column ... notation always define aliases matching names from entity. For example this code won't work properly (projection will return nulls for each getter):

@Query(value = "SELECT user.firstname, user.lastname FROM SD_User user WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);

But this works fine:

@Query(value = "SELECT user.firstname AS firstname, user.lastname AS lastname FROM SD_User user WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);

In case of more complex queries I'd rather use JdbcTemplate with custom repository instead.

What does 'git remote add upstream' help achieve?

This is useful when you have your own origin which is not upstream. In other words, you might have your own origin repo that you do development and local changes in and then occasionally merge upstream changes. The difference between your example and the highlighted text is that your example assumes you're working with a clone of the upstream repo directly. The highlighted text assumes you're working on a clone of your own repo that was, presumably, originally a clone of upstream.

TortoiseSVN icons overlay not showing after updating to Windows 10

Had same issue, and was solved by running regedit, erasing some entries in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\ShellIconOverlayIdentifiers and restarting. Deleting OneDrive1... enties was not permited, but I had some from Google Drive. You can also make a bakup by double-clicking in the registry directory and doing an "Export" to a file.

On Windows 10, most of the entries are used by OneDrive and you won't have permission to remove them. In order to do so, right click on the entry (Example: "OneDrive1", then click "Advanced", then click the link labled "Change" at the very top next to "Owner". This lets you change the owner. Type in your username and hit OK. Now give yourself "Full Control" and then apply it. Now you should be able to delete or rename it.

html5 - canvas element - Multiple layers

I was having this same problem too, I while multiple canvas elements with position:absolute does the job, if you want to save the output into an image, that's not going to work.

So I went ahead and did a simple layering "system" to code as if each layer had its own code, but it all gets rendered into the same element.

https://github.com/federicojacobi/layeredCanvas

I intend to add extra capabilities, but for now it will do.

You can do multiple functions and call them in order to "fake" layers.

How to get the first word of a sentence in PHP?

$str='<?php $myvalue = Test me more; ?>';
$s = preg_split("/= *(.[^ ]*?) /", $str,-1,PREG_SPLIT_DELIM_CAPTURE);
print $s[1];

Get human readable version of file size?

I like the fixed precision of senderle's decimal version, so here's a sort of hybrid of that with joctee's answer above (did you know you could take logs with non-integer bases?):

from math import log
def human_readable_bytes(x):
    # hybrid of https://stackoverflow.com/a/10171475/2595465
    #      with https://stackoverflow.com/a/5414105/2595465
    if x == 0: return '0'
    magnitude = int(log(abs(x),10.24))
    if magnitude > 16:
        format_str = '%iP'
        denominator_mag = 15
    else:
        float_fmt = '%2.1f' if magnitude % 3 == 1 else '%1.2f'
        illion = (magnitude + 1) // 3
        format_str = float_fmt + ['', 'K', 'M', 'G', 'T', 'P'][illion]
    return (format_str % (x * 1.0 / (1024 ** illion))).lstrip('0')

String to Binary in C#

Here's an extension function:

        public static string ToBinary(this string data, bool formatBits = false)
        {
            char[] buffer = new char[(((data.Length * 8) + (formatBits ? (data.Length - 1) : 0)))];
            int index = 0;
            for (int i = 0; i < data.Length; i++)
            {
                string binary = Convert.ToString(data[i], 2).PadLeft(8, '0');
                for (int j = 0; j < 8; j++)
                {
                    buffer[index] = binary[j];
                    index++;
                }
                if (formatBits && i < (data.Length - 1))
                {
                    buffer[index] = ' ';
                    index++;
                }
            }
            return new string(buffer);
        }

You can use it like:

Console.WriteLine("Testing".ToBinary());

and if you add 'true' as a parameter, it will automatically separate each binary sequence.

Trim last character from a string

you could also use this:

public static class Extensions
 {

        public static string RemovePrefix(this string o, string prefix)
        {
            if (prefix == null) return o;
            return !o.StartsWith(prefix) ? o : o.Remove(0, prefix.Length);
        }

        public static string RemoveSuffix(this string o, string suffix)
        {
            if(suffix == null) return o;
            return !o.EndsWith(suffix) ? o : o.Remove(o.Length - suffix.Length, suffix.Length);
        }

    }

How do I access named capturing groups in a .NET Regex?

The following code sample, will match the pattern even in case of space characters in between. i.e. :

<td><a href='/path/to/file'>Name of File</a></td>

as well as:

<td> <a      href='/path/to/file' >Name of File</a>  </td>

Method returns true or false, depending on whether the input htmlTd string matches the pattern or no. If it matches, the out params contain the link and name respectively.

/// <summary>
/// Assigns proper values to link and name, if the htmlId matches the pattern
/// </summary>
/// <returns>true if success, false otherwise</returns>
public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
    link = null;
    name = null;

    string pattern = "<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>";

    if (Regex.IsMatch(htmlTd, pattern))
    {
        Regex r = new Regex(pattern,  RegexOptions.IgnoreCase | RegexOptions.Compiled);
        link = r.Match(htmlTd).Result("${link}");
        name = r.Match(htmlTd).Result("${name}");
        return true;
    }
    else
        return false;
}

I have tested this and it works correctly.

Can I create view with parameter in MySQL?

CREATE VIEW MyView AS
   SELECT Column, Value FROM Table;


SELECT Column FROM MyView WHERE Value = 1;

Is the proper solution in MySQL, some other SQLs let you define Views more exactly.

Note: Unless the View is very complicated, MySQL will optimize this just fine.

How to inflate one view with a layout

Even simpler way is to use

View child = View.inflate(context, R.layout.child, null)
item.addChild(child) //attach to your item

'Missing contentDescription attribute on image' in XML

This warning tries to improve accessibility of your application.

To disable missing content description warning in the whole project, you can add this to your application module build.gradle

android {

    ...

    lintOptions {
        disable 'ContentDescription'
    }
}

How to return a PNG image from Jersey REST service method to the browser

I'm not convinced its a good idea to return image data in a REST service. It ties up your application server's memory and IO bandwidth. Much better to delegate that task to a proper web server that is optimized for this kind of transfer. You can accomplish this by sending a redirect to the image resource (as a HTTP 302 response with the URI of the image). This assumes of course that your images are arranged as web content.

Having said that, if you decide you really need to transfer image data from a web service you can do so with the following (pseudo) code:

@Path("/whatever")
@Produces("image/png")
public Response getFullImage(...) {

    BufferedImage image = ...;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos);
    byte[] imageData = baos.toByteArray();

    // uncomment line below to send non-streamed
    // return Response.ok(imageData).build();

    // uncomment line below to send streamed
    // return Response.ok(new ByteArrayInputStream(imageData)).build();
}

Add in exception handling, etc etc.

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

try this.. i had the same issue, below implementation worked for me

Reader reader = Files.newBufferedReader(Paths.get(<yourfilewithpath>), StandardCharsets.ISO_8859_1);

then use Reader where ever you want.

foreg:

CsvToBean<anyPojo> csvToBean = null;
    try {
        Reader reader = Files.newBufferedReader(Paths.get(csvFilePath), 
                        StandardCharsets.ISO_8859_1);
        csvToBean = new CsvToBeanBuilder(reader)
                .withType(anyPojo.class)
                .withIgnoreLeadingWhiteSpace(true)
                .withSkipLines(1)
                .build();

    } catch (IOException e) {
        e.printStackTrace();
    }

format a number with commas and decimals in C# (asp.net MVC3)

CultureInfo us = new CultureInfo("en-US");
TotalAmount.ToString("N", us)

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

In my case I have pushed changes to origin/master and then realised I should not have done so :-( This was complicated by the fact that the local changes were in a subtree. So I went back to the last good commit before the "bad" local changes (using SourceTree) and then I got the "divergence message".

After fixing my mess locally (the details are not important here) I wanted to "move back in time" the remote origin/master branch so that it would be in sync with the local master again. The solution in my case was:

git push origin master -f

Note the -f (force) switch. This deleted the "bad changes" that had been pushed to origin/master by mistake and now the local and remote branches are in sync.

Please keep in mind that this is a potentially destructive operation so perform it only if you are 100% sure that "moving back" the remote master in time is OK.

How to validate Google reCAPTCHA v3 on server side?

Check below example

<script src='https://www.google.com/recaptcha/api.js'></script>
<script>

function get_action(form) 
{
    var v = grecaptcha.getResponse();
    if(v.length == 0)
    {
        document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
        return false;
    }
    else
    {
         document.getElementById('captcha').innerHTML="Captcha completed";
        return true; 
    }
}

</script>
<form autocomplete="off" method="post" action=submit.php">

    <input type="text" name="name">
    <input type="text" name="email">
    <div class="g-recaptcha" id="rcaptcha"  data-sitekey="site key"></div>
    <span id="captcha" style="color:red" /></span> <!-- this will show captcha errors -->
    <input type="submit" id="sbtBrn" value="Submit" name="sbt" class="btn btn-info contactBtn" />
</form>

Property 'value' does not exist on type EventTarget in TypeScript

The way I do it is the following (better than type assertion imho):

onFieldUpdate(event: { target: HTMLInputElement }) {
  this.$emit('onFieldUpdate', event.target.value);
}

This assumes you are only interested in the target property, which is the most common case. If you need to access the other properties of event, a more comprehensive solution involves using the & type intersection operator:

event: Event & { target: HTMLInputElement }

This is a Vue.js version but the concept applies to all frameworks. Obviously you can go more specific and instead of using a general HTMLInputElement you can use e.g. HTMLTextAreaElement for textareas.

Create Directory if it doesn't exist with Ruby

You are probably trying to create nested directories. Assuming foo does not exist, you will receive no such file or directory error for:

Dir.mkdir 'foo/bar'
# => Errno::ENOENT: No such file or directory - 'foo/bar'

To create nested directories at once, FileUtils is needed:

require 'fileutils'
FileUtils.mkdir_p 'foo/bar'
# => ["foo/bar"]

Edit2: you do not have to use FileUtils, you may do system call (update from @mu is too short comment):

> system 'mkdir', '-p', 'foo/bar' # worse version: system 'mkdir -p "foo/bar"'
=> true

But that seems (at least to me) as worse approach as you are using external 'tool' which may be unavailable on some systems (although I can hardly imagine system without mkdir, but who knows).

How to query as GROUP BY in django?

An easy solution, but not the proper way is to use raw SQL:

results = Members.objects.raw('SELECT * FROM myapp_members GROUP BY designation')

Another solution is to use the group_by property:

query = Members.objects.all().query
query.group_by = ['designation']
results = QuerySet(query=query, model=Members)

You can now iterate over the results variable to retrieve your results. Note that group_by is not documented and may be changed in future version of Django.

And... why do you want to use group_by? If you don't use aggregation, you can use order_by to achieve an alike result.

How to check if a date is greater than another in Java?

You can use Date.before() or Date.after() or Date.equals() for date comparison.

Taken from here:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDiff {

    public static void main( String[] args )
    {
        compareDates("2017-01-13 00:00:00", "2017-01-14 00:00:00");// output will be Date1 is before Date2
        compareDates("2017-01-13 00:00:00", "2017-01-12 00:00:00");//output will be Date1 is after Date2
        compareDates("2017-01-13 00:00:00", "2017-01-13 10:20:30");//output will be Date1 is before Date2 because date2 is ahead of date 1 by 10:20:30 hours
        compareDates("2017-01-13 00:00:00", "2017-01-13 00:00:00");//output will be Date1 is equal Date2 because both date and time are equal
    }

    public static void compareDates(String d1,String d2)
    {
        try{
            // If you already have date objects then skip 1

            //1
            // Create 2 dates starts
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(d2);

            System.out.println("Date1"+sdf.format(date1));
            System.out.println("Date2"+sdf.format(date2));System.out.println();

            // Create 2 dates ends
            //1

            // Date object is having 3 methods namely after,before and equals for comparing
            // after() will return true if and only if date1 is after date 2
            if(date1.after(date2)){
                System.out.println("Date1 is after Date2");
            }
            // before() will return true if and only if date1 is before date2
            if(date1.before(date2)){
                System.out.println("Date1 is before Date2");
            }

            //equals() returns true if both the dates are equal
            if(date1.equals(date2)){
                System.out.println("Date1 is equal Date2");
            }

            System.out.println();
        }
        catch(ParseException ex){
            ex.printStackTrace();
        }
    }

    public static void compareDates(Date date1,Date date2)
    {
        // if you already have date objects then skip 1
        //1

        //1

        //date object is having 3 methods namely after,before and equals for comparing
        //after() will return true if and only if date1 is after date 2
        if(date1.after(date2)){
            System.out.println("Date1 is after Date2");
        }

        //before() will return true if and only if date1 is before date2
        if(date1.before(date2)){
            System.out.println("Date1 is before Date2");
        }

        //equals() returns true if both the dates are equal
        if(date1.equals(date2)){
            System.out.println("Date1 is equal Date2");
        }

        System.out.println();
    }
}

Locate current file in IntelliJ

There is no direct shortcut for such operation in IntelliJ IDEA 14 but you can install the plugin and set it the keyboard shortcut to the function that called "Scroll From Source" in keymap settings.

enter image description here

Safely remove migration In Laravel

DO NOT run php artisan migrate:fresh that's gonna drop all the tables

return in for loop or outside loop

Now someone told me that this is not very good programming because I use the return statement inside a loop and this would cause garbage collection to malfunction.

That's incorrect, and suggests you should treat other advice from that person with a degree of skepticism.

The mantra of "only have one return statement" (or more generally, only one exit point) is important in languages where you have to manage all resources yourself - that way you can make sure you put all your cleanup code in one place.

It's much less useful in Java: as soon as you know that you should return (and what the return value should be), just return. That way it's simpler to read - you don't have to take in any of the rest of the method to work out what else is going to happen (other than finally blocks).

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

As the error says your router link should match the existing routes configured

It should be just routerLink="/about"

How should I do integer division in Perl?

you can:

use integer;

it is explained by Michael Ratanapintha or else use manually:

$a=3.7;
$b=2.1;

$c=int(int($a)/int($b));

notice, 'int' is not casting. this is function for converting number to integer form. this is because Perl 5 does not have separate integer division. exception is when you 'use integer'. Then you will lose real division.

In Chart.js set chart title, name of x axis and y axis?

          <Scatter
            data={data}
            // style={{ width: "50%", height: "50%" }}
            options={{
              scales: {
                yAxes: [
                  {
                    scaleLabel: {
                      display: true,
                      labelString: "Probability",
                    },
                  },
                ],
                xAxes: [
                  {
                    scaleLabel: {
                      display: true,
                      labelString: "Hours",
                    },
                  },
                ],
              },
            }}
          />

How do I escape double and single quotes in sed?

You can use %

sed -i "s%http://www.fubar.com%URL_FUBAR%g"

How do I enable MSDTC on SQL Server?

I've found that the best way to debug is to use the microsoft tool called DTCPing

  1. Copy the file to both the server (DB) and the client (Application server/client pc)
    • Start it at the server and the client
    • At the server: fill in the client netbios computer name and try to setup a DTC connection
    • Restart both applications.
    • At the client: fill in the server netbios computer name and try to setup a DTC connection

I've had my fare deal of problems in our old company network, and I've got a few tips:

  • if you get the error message "Gethostbyname failed" it means the computer can not find the other computer by its netbios name. The server could for instance resolve and ping the client, but that works on a DNS level. Not on a netbios lookup level. Using WINS servers or changing the LMHOST (dirty) will solve this problem.
  • if you get an error "Acces Denied", the security settings don't match. You should compare the security tab for the msdtc and get the server and client to match. One other thing to look at is the RestrictRemoteClients value. Depending on your OS version and more importantly the Service Pack, this value can be different.
  • Other connection problems:
    • The firewall between the server and the client must allow communication over port 135. And more importantly the connection can be initiated from both sites (I had a lot of problems with the firewall people in my company because they assumed only the server would open an connection on to that port)
    • The protocol returns a random port to connect to for the real transaction communication. Firewall people don't like that, they like to restrict the ports to a certain range. You can restrict the RPC dynamic port generation to a certain range using the keys as described in How to configure RPC dynamic port allocation to work with firewalls.

In my experience, if the DTCPing is able to setup a DTC connection initiated from the client and initiated from the server, your transactions are not the problem any more.

using javascript to detect whether the url exists before display in iframe

You could test the url via AJAX and read the status code - that is if the URL is in the same domain.

If it's a remote domain, you could have a server script on your own domain check out a remote URL.

Spring MVC - HttpMediaTypeNotAcceptableException

For me the problem was the URL I was trying to access. I had url like this:

{{ip}}:{{port}}/{{path}}/person.html

When you end url with .html it means that you will not accept any other payload than html. I needed to remove .html from the end for my endpoint to work properly. (You can also append .json at the end of url and it will work too)

Additionally your url-pattern in web.xml need to be configured properly to allow you to access the resource. For me it is

<servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Previously I had *.html* and it was preventing me an access to the endpoint.

How to subtract X days from a date using Java calendar?

Eli Courtwright second solution is wrong, it should be:

Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, -days);
date.setTime(c.getTime().getTime());

Automatically deleting related rows in Laravel (Eloquent ORM)

Relation in User model:

public function photos()
{
    return $this->hasMany('Photo');
}

Delete record and related:

$user = User::find($id);

// delete related   
$user->photos()->delete();

$user->delete();

how to sort order of LEFT JOIN in SQL query?

This will get you the most expensive car for the user:

SELECT users.userName, MAX(cars.carPrice)
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName

However, this statement makes me think that you want all of the cars prices sorted, descending:

So question: How do I set the LEFT JOIN table to be ordered by carPrice, DESC ?

So you could try this:

SELECT users.userName, cars.carPrice
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
ORDER BY users.userName ASC, cars.carPrice DESC

What are the differences between a pointer variable and a reference variable in C++?

A reference is an alias for another variable whereas a pointer holds the memory address of a variable. References are generally used as function parameters so that the passed object is not the copy but the object itself.

    void fun(int &a, int &b); // A common usage of references.
    int a = 0;
    int &b = a; // b is an alias for a. Not so common to use. 

Variables as commands in bash scripts

There is a point to only put commands and options in variables.

#! /bin/bash

if [ $# -ne 2 ]
then
    echo "Usage: `basename $0` DIRECTORY BACKUP_DIRECTORY"
    exit 1
fi

. standard_tools    

directory=$1
backup_directory=$2
current_date=$(date +%Y-%m-%dT%H-%M-%S)
backup_file="${backup_directory}/${current_date}.backup"

${tar_create} "${directory}" | ${openssl} | ${split_1024} "$backup_file"

You can relocate the commands to another file you source, so you can reuse the same commands and options across many scripts. This is very handy when you have a lot of scripts and you want to control how they all use tools. So standard_tools would contain:

export tar_create="tar cv"
export openssl="openssl des3 -salt"
export split_1024="split -b 1024m -"

How to SELECT by MAX(date)?

It works great for me

SELECT report_id,computer_id,MAX(date_entered) FROM reports GROUP BY computer_id

Vuejs: v-model array in multiple input

Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    users: [{ name: 'sajadweb',email:'[email protected]' }] _x000D_
  },_x000D_
  methods: {_x000D_
    addUser: function () {_x000D_
      this.users.push({ name: '',email:'' });_x000D_
    },_x000D_
    deleteUser: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.users.splice(index, 1);_x000D_
      if(index===0)_x000D_
      this.addUser()_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Add user</h1>_x000D_
  <div v-for="(user, index) in users">_x000D_
    <input v-model="user.name">_x000D_
    <input v-model="user.email">_x000D_
    <button @click="deleteUser(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addUser">_x000D_
    New User_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

Try starting IntelliJ from terminal. You can find application file under: /Applications/IntelliJ\ IDEA\ 14.app/Contents/MacOS

How to install OpenSSL in windows 10?

Either set the openssl present in Git as your default openssl and include that into your path in environmental variables (quick way)

OR

  1. Install the system-specific openssl from this link.
  2. set the following variable : set OPENSSL_CONF=LOCATION_OF_SSL_INSTALL\bin\openssl.cfg
  3. Update the path : set Path=...Other Values here...;LOCATION_OF_SSL_INSTALL\bin

Find unused code

I would also mention that using IOC aka Unity may make these assessments misleading. I may have erred but several very important classes that are instantiated via Unity appear to have no instantiation as far as ReSharper can tell. If I followed the ReSharper recommendations I would get hosed!

How can I get color-int from color resource?

I updated to use ContextCompat.getColor(context, R.color.your_color); but sometimes (On some devices/Android versions. I'm not sure) that causes a NullPointerExcepiton.

So to make it work on all devices/versions, I fall back on the old way of doing it, in the case of a null pointer.

try {
    textView.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_grey_dark));
}
catch(NullPointerException e) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        textView.setTextColor(getContext().getColor(R.color.text_grey_dark));
    }
    else {
        textView.setTextColor(getResources().getColor(R.color.text_grey_dark));
    }
}

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

Different ways of loading a file as an InputStream

All these answers around here, as well as the answers in this question, suggest that loading absolute URLs, like "/foo/bar.properties" treated the same by class.getResourceAsStream(String) and class.getClassLoader().getResourceAsStream(String). This is NOT the case, at least not in my Tomcat configuration/version (currently 7.0.40).

MyClass.class.getResourceAsStream("/foo/bar.properties"); // works!  
MyClass.class.getClassLoader().getResourceAsStream("/foo/bar.properties"); // does NOT work!

Sorry, I have absolutely no satisfying explanation, but I guess that tomcat does dirty tricks and his black magic with the classloaders and cause the difference. I always used class.getResourceAsStream(String) in the past and haven't had any problems.

PS: I also posted this over here

How do you connect localhost in the Android emulator?

Instead of giving localhost give the IP.

Java escape JSON String?

The JSON specification at https://www.json.org/ is very simple by design. Escaping characters in JSON strings is not hard. This code works for me:

private String escape(String raw) {
    String escaped = raw;
    escaped = escaped.replace("\\", "\\\\");
    escaped = escaped.replace("\"", "\\\"");
    escaped = escaped.replace("\b", "\\b");
    escaped = escaped.replace("\f", "\\f");
    escaped = escaped.replace("\n", "\\n");
    escaped = escaped.replace("\r", "\\r");
    escaped = escaped.replace("\t", "\\t");
    // TODO: escape other non-printing characters using uXXXX notation
    return escaped;
}

Dart: mapping a list (list.map)

Yes, You can do it this way too

 List<String> listTab = new List();
 map.forEach((key, val) {
  listTab.add(val);
 });

 //your widget//
 bottom: new TabBar(
  controller: _controller,
  isScrollable: true,
  tabs: listTab
  ,
),

RegEx match open tags except XHTML self-contained tags

It's true that when programming it's usually best to use dedicated parsers and APIs instead of regular expressions when dealing with HTML, especially if accuracy is paramount (e.g., if your processing might have security implications). However, I don’t ascribe to a dogmatic view that XML-style markup should never be processed with regular expressions. There are cases when regular expressions are a great tool for the job, such as when making one-time edits in a text editor, fixing broken XML files, or dealing with file formats that look like but aren’t quite XML. There are some issues to be aware of, but they're not insurmountable or even necessarily relevant.

A simple regex like <([^>"']|"[^"]*"|'[^']*')*> is usually good enough, in cases such as those I just mentioned. It's a naive solution, all things considered, but it does correctly allow unencoded > symbols in attribute values. If you're looking for, e.g., a table tag, you could adapt it as </?table\b([^>"']|"[^"]*"|'[^']*')*>.

Just to give a sense of what a more "advanced" HTML regex would look like, the following does a fairly respectable job of emulating real-world browser behavior and the HTML5 parsing algorithm:

</?([A-Za-z][^\s>/]*)(?:=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)|[^>])*(?:>|$)

The following matches a fairly strict definition of XML tags (although it doesn't account for the full set of Unicode characters allowed in XML names):

<(?:([_:A-Z][-.:\w]*)(?:\s+[_:A-Z][-.:\w]*\s*=\s*(?:"[^"]*"|'[^']*'))*\s*/?|/([_:A-Z][-.:\w]*)\s*)>

Granted, these don't account for surrounding context and a few edge cases, but even such things could be dealt with if you really wanted to (e.g., by searching between the matches of another regex).

At the end of the day, use the most appropriate tool for the job, even in the cases when that tool happens to be a regex.

SQL: sum 3 columns when one column has a null value?

I would try this:

select sum (case when TotalHousM is null then 0 else TotalHousM end)
       + (case when TotalHousT is null then 0 else TotalHousT end)
       + (case when TotalHousW is null then 0 else TotalHousW end)
       + (case when TotalHousTH is null then 0 else TotalHousTH end)
       + (case when TotalHousF is null then 0 else TotalHousF end)
       as Total
From LeaveRequest

what does "dead beef" mean?

It was used as a pattern to store in memory as a series of hex bytes (0xde, 0xad, 0xbe, 0xef). You could see if memory was corrupted because of hardware failure, buffer overruns, etc.

Detect changes in the DOM

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // ...
});

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true
  //...
});

Complete explanations: https://stackoverflow.com/a/11546242/6569224

How to use a decimal range() step value?

[x * 0.1 for x in range(0, 10)] 

in Python 2.7x gives you the result of:

[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

but if you use:

[ round(x * 0.1, 1) for x in range(0, 10)]

gives you the desired:

[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

The representation of if-elseif-else in EL using JSF

The following code the easiest way:

 <h:outputLabel value="value = 10" rendered="#{row == 10}" /> 
 <h:outputLabel value="value = 15" rendered="#{row == 15}" /> 
 <h:outputLabel value="value xyz" rendered="#{row != 15 and row != 10}" /> 

Link for EL expression syntax. http://developers.sun.com/docs/jscreator/help/jsp-jsfel/jsf_expression_language_intro.html#syntax

Losing scope when using ng-include

I've figured out how to work around this issue without mixing parent and sub scope data. Set a ng-if on the the ng-include element and set it to a scope variable. For example :

<div ng-include="{{ template }}" ng-if="show"/>

In your controller, when you have set all the data you need in your sub scope, then set show to true. The ng-include will copy at this moment the data set in your scope and set it in your sub scope.

The rule of thumb is to reduce scope data deeper the scope are, else you have this situation.

Max

SQLite add Primary Key

I used the CREATE TABLE AS syntax to merge several columns and encountered the same problem. Here is an AppleScript I wrote to speed the process up.

set databasePath to "~/Documents/Databases/example.db"
set tableOne to "separate" -- Table from which you are pulling data
set tableTwo to "merged" -- Table you are creating
set {tempCol, tempColEntry, permColEntry} to {{}, {}, {}}
set permCol to {"id integer primary key"}

-- Columns are created from single items  AND from the last item of a list
-- {{"a", "b", "c"}, "d", "e"} Columns "a" and "b" will be merged into a new column "c".  tableTwo will have columns "c", "d", "e"

set nonCoal to {"City", "Contact", "Names", {"Address 1", "Address", "address one", "Address1", "Text4", "Address 1"}, {"E-Mail", "E-Mail Address", "Email", "Email Address", "EmailAddress", "Email"}, {"Zip", "Zip Code", "ZipCode", "Zip"}, {"Telephone", "BusinessPhone", "Phone", "Work Phone", "Telephone"}, {"St", "State", "State"}, {"Salutation", "Mr/Ms", "Mr/s", "Salutations", "Sautation", "Salutation"}}

-- Build the COALESCE statements
repeat with h from 1 to count of nonCoal
set aColumn to item h of nonCoal
if class of aColumn is not list then
    if (count of words of aColumn) > 1 then set aColumn to quote & aColumn & quote
    set end of tempCol to aColumn
    set end of permCol to aColumn
else
    set coalEntry to {}
    repeat with i from 1 to count of aColumn
        set coalCol to item i of aColumn as string
        if (count of words of coalCol) > 1 then set coalCol to quote & coalCol & quote
        if i = 1 then
            set end of coalEntry to "TRIM(COALESCE(" & coalCol & ", '') || \" \" || "
        else if i < ((count of aColumn) - 1) then
            set end of coalEntry to "COALESCE(" & coalCol & ", '') || \" \" || "
        else if i = ((count of aColumn) - 1) then
            set as_Col to item (i + 1) of aColumn as string
            if (count of words of as_Col) > 1 then set as_Col to quote & as_Col & quote
            set end of coalEntry to ("COALESCE(" & coalCol & ", '')) AS " & as_Col) & ""
            set end of permCol to as_Col
        end if
    end repeat
    set end of tempCol to (coalEntry as string)
end if
end repeat

-- Since there are ", '' within the COALESCE statement, you can't use "TID" and "as string" to convert tempCol and permCol for entry into sqlite3. I rebuild the lists in the next block.
repeat with j from 1 to count of tempCol
if j < (count of tempCol) then
    set end of tempColEntry to item j of tempCol & ", "
    set end of permColEntry to item j of permCol & ", "
else
    set end of tempColEntry to item j of tempCol
    set end of permColEntry to item j of permCol
end if
end repeat
set end of permColEntry to ", " & item (j + 1) of permCol
set permColEntry to (permColEntry as string)
set tempColEntry to (tempColEntry as string)

-- Create the new table with an "id integer primary key" column
set createTable to "create table " & tableTwo & " (" & permColEntry & "); "
do shell script "sqlite3 " & databasePath & space & quoted form of createTable

-- Create a temporary table and then populate the permanent table
set createTemp to "create temp table placeholder as select " & tempColEntry & " from " & tableOne & ";  " & "insert into " & tableTwo & " select Null, * from placeholder;"
do shell script "sqlite3 " & databasePath & space & quoted form of createTemp

--export the new table as a .csv file
do shell script "sqlite3 -header -column -csv " & databasePath & " \"select * from " & tableTwo & " ; \"> ~/" & tableTwo & ".csv"

Initializing a member array in constructor initializer

  1. How can I do what I want to do (that is, initialize an array in a constructor (not assigning elements in the body)). Is it even possible?

Yes. It's using a struct that contains an array. You say you already know about that, but then I don't understand the question. That way, you do initialize an array in the constructor, without assignments in the body. This is what boost::array does.

Does the C++03 standard say anything special about initializing aggregates (including arrays) in ctor initializers? Or the invalidness of the above code is a corollary of some other rules?

A mem-initializer uses direct initialization. And the rules of clause 8 forbid this kind of thing. I'm not exactly sure about the following case, but some compilers do allow it.

struct A {
  char foo[6];
  A():foo("hello") { } /* valid? */
};

See this GCC PR for further details.

Do C++0x initializer lists solve the problem?

Yes, they do. However your syntax is invalid, I think. You have to use braces directly to fire off list initialization

struct A {
  int foo[3];
  A():foo{1, 2, 3} { }
  A():foo({1, 2, 3}) { } /* invalid */
};