Programs & Examples On #Dbmetal

How to detect Adblock on my website?

I've not seen any good, simple answers that address both of the two types of ad blockers in prevalent use today, so I'll provide my own answer.

Ad blocker type 1: Blocks web advertisement scripts based upon the script name (AdBlock, uBlock origin etc.).

Ad blocker type 2: Blocks web advertisements based upon a database of ad serving host names (FireFox content blocker, various gateway plugins, etc).

This solution works for both. It throws up a big pink "appeal box" asking users to disable their ad blocker. We like to place it below the menus and above the content. We don't actually block access to the site - this just pushes the content down on the page a bit, but people will find it annoying just enough that virtually all will comply and disable their ad blocker on your site.

enter image description here

So here is the solution:

A) Create a file named advertisement.js and place it in the root of your web server, consisting of the following line of code:

document.write('<div id="tester">an advertisement</div>');

B) Inject the following into your web pages (you might even use your ad server code to do this!). Suggested location is below the menus and above the content.

<script src="advertisement.js"></script>
<table id="tbl_ab_appeal" style="width: 900px; margin-left:auto; margin-right: auto; padding: 25px; background: #FCC; border: 1px solid #F66; visibility:collapse; border-collapse: collapse;">
    <tr>
        <td>We've detected that you're using an <strong>ad content blocking</strong> browser plug-in or feature. Ads provide a critical source of revenue to the continued operation of [This website name].&nbsp; We ask that you disable ad blocking while on [This
            website name] in the best interests of our community.</td>
    </tr>
</table>
<script>
    if (document.getElementById("tester") == undefined) adsBlocked();

    function adsBlocked() {
        document.getElementById("tbl_ab_appeal").style.visibility = "visible";
        document.getElementById("tbl_ab_appeal").style.borderCollapse = "separate";
        document.getElementById("tbl_ab_appeal").style.marginTop = "10px"
        document.getElementById("tbl_ab_appeal").style.marginBottom = "10px"
    }
</script>
<script onerror="adsBlocked()" src="//www.googletagservices.com/tag/js/gpt.js"></script>

How does it work? The message is loaded, but made zero height and invisible. If either the local script advertisement.js fails to run, or the remote AdSense script www.googletagservices.com/tag/js/gpt.js fails to load, the box is made visible.

Disabling Chrome Autofill

My problem was that Chrome would autofill postal code, over the Bootstrap autocomplete interface as I was auto suggesting possible values from my database.

Things I had to do:

  • Change input field's id property to something other than "postcode"
  • Change input field's autocomplete value to false
  • After calling $('#postcode_field').autocomplete(...) I had to reset the autocomplete property with $('#postcode_field').prop('autocomplete', 'false'); because Boostrap's autocomplete plugin changes it to off automatically.

How to switch back to 'master' with git?

You need to checkout the branch:

git checkout master

See the Git cheat sheets for more information.

Edit: Please note that git does not manage empty directories, so you'll have to manage them yourself. If your directory is empty, just remove it directly.

How to check whether a given string is valid JSON in Java

Here is a working example for strict json parsing with gson library:

public static JsonElement parseStrict(String json) {
    // throws on almost any non-valid json
    return new Gson().getAdapter(JsonElement.class).fromJson(json); 
}

See also my other detailed answer in How to check if JSON is valid in Java using GSON with more info and extended test case with various non-valid examples.

Extract csv file specific columns to list in Python

A standard-lib version (no pandas)

This assumes that the first row of the csv is the headers

import csv

# open the file in universal line ending mode 
with open('test.csv', 'rU') as infile:
  # read the file as a dictionary for each row ({header : value})
  reader = csv.DictReader(infile)
  data = {}
  for row in reader:
    for header, value in row.items():
      try:
        data[header].append(value)
      except KeyError:
        data[header] = [value]

# extract the variables you want
names = data['name']
latitude = data['latitude']
longitude = data['longitude']

Getting the array length of a 2D array in Java

It was really hard to remember that

    int numberOfColumns = arr.length;
    int numberOfRows = arr[0].length;

Let's understand why this is so and how we can figure this out when we're given an array problem. From the below code we can see that rows = 4 and columns = 3:

    int[][] arr = { {1, 1, 1, 1}, 

                    {2, 2, 2, 2}, 

                    {3, 3, 3, 3} };

arr has multiple arrays in it, and these arrays can be arranged in a vertical manner to get the number of columns. To get the number of rows, we need to access the first array and consider its length. In this case, we access [1, 1, 1, 1] and thus, the number of rows = 4. When you're given a problem where you can't see the array, you can visualize the array as a rectangle with n X m dimensions and conclude that we can get the number of rows by accessing the first array then its length. The other one (arr.length) is for the columns.

how to convert date to a format `mm/dd/yyyy`

Use:

select convert(nvarchar(10), CREATED_TS, 101)

or

select format(cast(CREATED_TS as date), 'MM/dd/yyyy') -- MySQL 3.23 and above

"R cannot be resolved to a variable"?

For me somehow the Project properties; Android; Project Build Target was not set. I chose a Android version there (e.g. 4.2) and it fixed it.

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Javascript add leading zeroes to date

Try this: http://jsfiddle.net/xA5B7/

var MyDate = new Date();
var MyDateString;

MyDate.setDate(MyDate.getDate() + 20);

MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
             + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
             + MyDate.getFullYear();

EDIT:

To explain, .slice(-2) gives us the last two characters of the string.

So no matter what, we can add "0" to the day or month, and just ask for the last two since those are always the two we want.

So if the MyDate.getMonth() returns 9, it will be:

("0" + "9") // Giving us "09"

so adding .slice(-2) on that gives us the last two characters which is:

("0" + "9").slice(-2)
"09"

But if MyDate.getMonth() returns 10, it will be:

("0" + "10") // Giving us "010"

so adding .slice(-2) gives us the last two characters, or:

("0" + "10").slice(-2)
"10"

Dropping a connected user from an Oracle 10g database schema

To find the sessions, as a DBA use

select sid,serial# from v$session where username = '<your_schema>'

If you want to be sure only to get the sessions that use SQL Developer, you can add and program = 'SQL Developer'. If you only want to kill sessions belonging to a specific developer, you can add a restriction on os_user

Then kill them with

alter system kill session '<sid>,<serial#>'

(e.g. alter system kill session '39,1232')

A query that produces ready-built kill-statements could be

select 'alter system kill session ''' || sid || ',' || serial# || ''';' from v$session where username = '<your_schema>'

This will return one kill statement per session for that user - something like:

alter system kill session '375,64855';

alter system kill session '346,53146';

How to cancel/abort jQuery AJAX request?

You can use jquery-validate.js . The following is the code snippet from jquery-validate.js.

// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()

var pendingRequests = {},
    ajax;
// Use a prefilter if available (1.5+)
if ( $.ajaxPrefilter ) {
    $.ajaxPrefilter(function( settings, _, xhr ) {
        var port = settings.port;
        if ( settings.mode === "abort" ) {
            if ( pendingRequests[port] ) {
                pendingRequests[port].abort();
            }
            pendingRequests[port] = xhr;
        }
    });
} else {
    // Proxy ajax
    ajax = $.ajax;
    $.ajax = function( settings ) {
        var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
            port = ( "port" in settings ? settings : $.ajaxSettings ).port;
        if ( mode === "abort" ) {
            if ( pendingRequests[port] ) {
                pendingRequests[port].abort();
            }
            pendingRequests[port] = ajax.apply(this, arguments);
            return pendingRequests[port];
        }
        return ajax.apply(this, arguments);
    };
}

So that you just only need to set the parameter mode to abort when you are making ajax request.

Ref:https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.js

Purpose of #!/usr/bin/python3 shebang

This line helps find the program executable that will run the script. This shebang notation is fairly standard across most scripting languages (at least as used on grown-up operating systems).

An important aspect of this line is specifying which interpreter will be used. On many development-centered Linux distributions, for example, it is normal to have several versions of python installed at the same time.

Python 2.x and Python 3 are not 100% compatible, so this difference can be very important. So #! /usr/bin/python and #! /usr/bin/python3 are not the same (and neither are quite the same as #! /usr/bin/env python3 as noted elsewhere on this page.

List an Array of Strings in alphabetical order

The first thing you tried seems to work fine. Here is an example program.
Press the "Start" button at the top of this page to run it to see the output yourself.

import java.util.Arrays;

public class Foo{
    public static void main(String[] args) {
        String [] stringArray = {"ab", "aB", "c", "0", "2", "1Ad", "a10"};
        orderedGuests(stringArray);
    }

    public static void orderedGuests(String[] hotel)
    {
        Arrays.sort(hotel);
        System.out.println(Arrays.toString(hotel));
    }
}

What does the NS prefix mean?

It is the NextStep (= NS) heritage. NeXT was the computer company that Steve Jobs formed after he quit Apple in 1985, and NextStep was it's operating system (UNIX based) together with the Obj-C language and runtime. Together with it's libraries and tools, NextStep was later renamed OpenStep (which was also the name on an API that NeXT developed together with Sun), which in turn later became Cocoa.

These different names are actually quite confusing (especially since some of the names differs only in which characters are upper or lower case..), try this for an explanation:

TheMerger OpenstepConfusion

Setting device orientation in Swift iOS

More Swift-like version:

override func shouldAutorotate() -> Bool {
    switch UIDevice.currentDevice().orientation {
    case .Portrait, .PortraitUpsideDown, .Unknown:
        return true
    default:
        return false
    }
}

override func supportedInterfaceOrientations() -> Int {
    return Int(UIInterfaceOrientationMask.Portrait.rawValue) | Int(UIInterfaceOrientationMask.PortraitUpsideDown.rawValue)
}

UINavigationController from Vivek Parihar

extension UINavigationController {
    public override func shouldAutorotate() -> Bool {
        return visibleViewController.shouldAutorotate()
    }
}

What's a standard way to do a no-op in python?

Use pass for no-op:

if x == 0:
  pass
else:
  print "x not equal 0"

And here's another example:

def f():
  pass

Or:

class c:
  pass

How do I URL encode a string

Try to use stringByAddingPercentEncodingWithAllowedCharacters method with [NSCharacterSet URLUserAllowedCharacterSet] it will cover all the cases

Objective C

NSString *value = @"Test / Test";
value = [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLUserAllowedCharacterSet]];

swift

var value = "Test / Test"
value.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLUserAllowedCharacterSet())

Output

Test%20%2F%20Test

Java: Finding the highest value in an array

void FindMax()
{
    int lessonNum;

    System.out.print("Enter your lesson numbers : ");
    lessonNum = input.nextInt();
    int[] numbers = new int[lessonNum];
    for (int i = 0; i < numbers.length; i++)
    {
        System.out.print("Please enter " + (i + 1) + " number : ");
        numbers[i] = input.nextInt();
    }
    double max = numbers[0];
    for (int i = 1; i < numbers.length; i++)
    {
        if (numbers[i] > max)
        {
            max = numbers[i];
        }
    }
    System.out.println("Maximum number is : " + max);
}

Redirect From Action Filter Attribute

Try the following snippet, it should be pretty clear:

public class AuthorizeActionFilterAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(FilterExecutingContext filterContext)
  {
    HttpSessionStateBase session = filterContext.HttpContext.Session;
    Controller controller = filterContext.Controller as Controller;

    if (controller != null)
    {
      if (session["Login"] == null)
      {
        filterContext.Cancel = true;
        controller.HttpContext.Response.Redirect("./Login");
      }
    }

    base.OnActionExecuting(filterContext);
  }
}

How to use Angular4 to set focus by element id

I also face same issue after some search I found a good solution as @GreyBeardedGeek mentioned that setTimeout is the key of this solution.He is totally correct. In your method you just need to add setTimeout and your problem will be solved.

setTimeout(() => this.inputEl.nativeElement.focus(), 0);

Random "Element is no longer attached to the DOM" StaleElementReferenceException

I was facing the same problem today and made up a wrapper class, which checks before every method if the element reference is still valid. My solution to retrive the element is pretty simple so i thought i'd just share it.

private void setElementLocator()
{
    this.locatorVariable = "selenium_" + DateTimeMethods.GetTime().ToString();
    ((IJavaScriptExecutor)this.driver).ExecuteScript(locatorVariable + " = arguments[0];", this.element);
}

private void RetrieveElement()
{
    this.element = (IWebElement)((IJavaScriptExecutor)this.driver).ExecuteScript("return " + locatorVariable);
}

You see i "locate" or rather save the element in a global js variable and retrieve the element if needed. If the page gets reloaded this reference will not work anymore. But as long as only changes are made to doom the reference stays. And that should do the job in most cases.

Also it avoids re-searching the element.

John

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

Android Studio 3.3 seems to have changed the shortcut to search for all references (find in path) on macOS.

In order to do that you should use Ctrl + Shift + F now (instead of Command + Shift + F as wrote on the previous answers):

UPDATE

To replace in path just use Ctrl + Shift + R.

enter image description here

C# delete a folder and all files and folders within that folder

Try:

System.IO.Directory.Delete(path,true)

This will recursively delete all files and folders underneath "path" assuming you have the permissions to do so.

How to find index of all occurrences of element in array?

const indexes = cars
    .map((car, i) => car === "Nano" ? i : null)
    .filter(i => i !== null)

Find most frequent value in SQL column

SELECT       `column`,
             COUNT(`column`) AS `value_occurrence` 
    FROM     `my_table`
    GROUP BY `column`
    ORDER BY `value_occurrence` DESC
    LIMIT    1;

Replace column and my_table. Increase 1 if you want to see the N most common values of the column.

Java, How to specify absolute value and square roots

Try using Math.abs:

variableAbs = Math.abs(variable);

For square root use:

variableSqRt = Math.sqrt(variable);

What's a "static method" in C#?

Shortly you can not instantiate the static class: Ex:

static class myStaticClass
{
    public static void someFunction()
    { /* */ }
}

You can not make like this:

myStaticClass msc = new myStaticClass();  // it will cause an error

You can make only:

myStaticClass.someFunction();

Cannot start session without errors in phpMyAdmin

The problem can be due to file and folder permissions; You can try changing the folder permissions:

sudo chmod 777 /var/lib/php/session/

This will set full read/write permissions on the PHP sessions folder.

Note: the php/session/ folder may be in a different location on some servers. Check your php.ini for your session path.

Java division by zero doesnt throw an ArithmeticException - why?

Why can't you just check it yourself and throw an exception if that is what you want.

    try {
        for (int i = 0; i < tab.length; i++) {
            tab[i] = 1.0 / tab[i];

            if (tab[i] == Double.POSITIVE_INFINITY ||
                    tab[i] == Double.NEGATIVE_INFINITY)
                throw new ArithmeticException();
        }
    } catch (ArithmeticException ae) {
        System.out.println("ArithmeticException occured!");
    }

Recover unsaved SQL query scripts

I use the free file searching program Everything, search for *.sql files across my C: drive, and then sort by Last Modified, and then browse by the date I think it was probably last executed.

It usually brings up loads of autorecovery files from a variety of locations. And you don't have to worry where the latest version of SSMS/VS is saving the backup files this version.

enter image description here

how to filter out a null value from spark dataframe

The following lines work well:

test.filter("friend_id is not null")

Count indexes using "for" in Python

Just use

for i in range(0, 5):
    print i

to iterate through your data set and print each value.

For large data sets, you want to use xrange, which has a very similar signature, but works more effectively for larger data sets. http://docs.python.org/library/functions.html#xrange

Singular matrix issue with Numpy

As it was already mentioned in previous answers, your matrix cannot be inverted, because its determinant is 0. But if you still want to get inverse matrix, you can use np.linalg.pinv, which leverages SVD to approximate initial matrix.

UIView Infinite 360 degree rotation animation?

Swift 5 UIView Extension using Keyframe Animations

This approach allows us to directly use the UIView.AnimationOptions.repeat

public extension UIView {

    func animateRotation(duration: TimeInterval, repeat: Bool, completion: ((Bool) -> ())?) {

        var options = UIView.KeyframeAnimationOptions(rawValue: UIView.AnimationOptions.curveLinear.rawValue)

        if `repeat` {
            options.insert(.repeat)
        }

        UIView.animateKeyframes(withDuration: duration, delay: 0, options: options, animations: {

            UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.25, animations: {
                self.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2)
            })

            UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.25, animations: {
                self.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
            })

            UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.25, animations: {
                self.transform = CGAffineTransform(rotationAngle: 3*CGFloat.pi/2)
            })

            UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25, animations: {
                self.transform = CGAffineTransform(rotationAngle: 2*CGFloat.pi)
            })

        }, completion: completion)

    }

}

How do I run a Python program in the Command Prompt in Windows 7?

First install the Python into your windows by using this url and then add path variable as

c:\python27

SQLite DateTime comparison

I had the same issue recently, and I solved it like this:

SELECT * FROM table WHERE 
    strftime('%s', date) BETWEEN strftime('%s', start_date) AND strftime('%s', end_date)

How to check if a value exists in an object using JavaScript

I did a test with all these examples, and I ran this in Node.js v8.11.2. Take this as a guide to select your best choice.

_x000D_
_x000D_
let i, tt;
    const obj = { a: 'test1', b: 'test2', c: 'test3', d: 'test4', e: 'test5', f: 'test6' };

console.time("test1")
i = 0;
for( ; i<1000000; i=i+1) {
  if (Object.values(obj).indexOf('test4') > -1) {
    tt = true;
  }
}
console.timeEnd("test1")

console.time("test1.1")
i = 0;
for( ; i<1000000 ; i=i+1) {
  if (~Object.values(obj).indexOf('test4')) {
    tt = true;
  }
}
console.timeEnd("test1.1")

console.time("test2")
i = 0;
for( ; i<1000000; i=i+1) {
  if (Object.values(obj).includes('test4')) {
    tt = true;
  }
}
console.timeEnd("test2")


console.time("test3")
i = 0;
for( ; i<1000000 ; i=i+1) {
  for(const item in obj) {
    if(obj[item] == 'test4') {
      tt = true;
      break;
    }
  }
}
console.timeEnd("test3")

console.time("test3.1")
i = 0;
for( ; i<1000000; i=i+1) {
  for(const [item, value] in obj) {
    if(value == 'test4') {
      tt = true;
      break;
    }
  }
}
console.timeEnd("test3.1")


console.time("test4")
i = 0;
for( ; i<1000000; i=i+1) {
  tt = Object.values(obj).some((val, val2) => {
    return val == "test4"
  });
}
console.timeEnd("test4")

console.time("test5")
i = 0;
for( ; i<1000000; i=i+1) {
  const arr = Object.keys(obj);
  const len = arr.length;
  let i2 = 0;
  for( ; i2<len ; i2=i2+1) {
    if(obj[arr[i2]] == "test4") {
      tt = true;
      break;
    }
  }
}
console.timeEnd("test5")
_x000D_
_x000D_
_x000D_

Output on my server

test1:   272.325 ms
test1.1: 246.316 ms
test2:   251.98 0ms
test3:    73.284 ms
test3.1: 102.029 ms
test4:   339.299 ms
test5:    85.527 ms

Multiple aggregations of the same column using pandas GroupBy.agg()

You can simply pass the functions as a list:

In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:         
           mean       sum
dummy                    
1      0.036901  0.369012

or as a dictionary:

In [21]: df.groupby('dummy').agg({'returns':
                                  {'Mean': np.mean, 'Sum': np.sum}})
Out[21]: 
        returns          
           Mean       Sum
dummy                    
1      0.036901  0.369012

"Application tried to present modally an active controller"?

Assume you have three view controllers instantiated like so:

UIViewController* vc1 = [[UIViewController alloc] init];
UIViewController* vc2 = [[UIViewController alloc] init];
UIViewController* vc3 = [[UIViewController alloc] init];

You have added them to a tab bar like this:

UITabBarController* tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:[NSArray arrayWithObjects:vc1, vc2, vc3, nil]];

Now you are trying to do something like this:

[tabBarController presentModalViewController:vc3];

This will give you an error because that Tab Bar Controller has a death grip on the view controller that you gave it. You can either not add it to the array of view controllers on the tab bar, or you can not present it modally.

Apple expects you to treat their UI elements in a certain way. This is probably buried in the Human Interface Guidelines somewhere as a "don't do this because we aren't expecting you to ever want to do this".

Where to put the gradle.properties file

Actually there are 3 places where gradle.properties can be placed:

  1. Under gradle user home directory defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle
  2. The sub-project directory (myProject2 in your case)
  3. The root project directory (under myProject)

Gradle looks for gradle.properties in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).

You can find more details about it in gradle documentation here.

How to get query parameters from URL in Angular 5?

If you're not using Angular router try, querystring. Install it

npm install --save querystring

to your project. In your component do something like this

import * as qs from 'querystring';
...
ngOnInit() {
   const params = qs.parse(window.location.search.substring(1));
   ...
}

The substring(1) is necessary because if you have something like this '/mypage?foo=bar' then the key name for will be ?foo

Add items to comboBox in WPF

Its better to build ObservableCollection and take advantage of it

public ObservableCollection<string> list = new ObservableCollection<string>();
list.Add("a");
list.Add("b");
list.Add("c");
this.cbx.ItemsSource = list;

cbx is comobobox name

Also Read : Difference between List, ObservableCollection and INotifyPropertyChanged

Trying to get property of non-object - CodeIgniter

To get the value:

$query = $this->db->query("YOUR QUERY");

Then, for single row from(in controller):

$query1 = $query->row();
$data['product'] = $query1;

In view, you can use your own code (above code)

Loop through a date range with JavaScript

Let us assume you got the start date and end date from the UI and stored it in the scope variable in the controller.

Then declare an array which will get reset on every function call so that on the next call for the function the new data can be stored.

var dayLabel = [];

Remember to use new Date(your starting variable) because if you dont use the new date and directly assign it to variable the setDate function will change the origional variable value in each iteration`

for (var d = new Date($scope.startDate); d <= $scope.endDate; d.setDate(d.getDate() + 1)) {
                dayLabel.push(new Date(d));
            }

I just assigned a variable, but echo $variable shows something else

Additional to putting the variable in quotation, one could also translate the output of the variable using tr and converting spaces to newlines.

$ echo $var | tr " " "\n"
foo
bar
baz

Although this is a little more convoluted, it does add more diversity with the output as you can substitute any character as the separator between array variables.

Example on ToggleButton

I think what are attempting is semantically same as a radio button when 1 is when one of the options is selected and 0 is the other option.

I suggest using the radio button provided by Android by default.

Here is how to use it- http://www.mkyong.com/android/android-radio-buttons-example/

and the android documentation is here-

http://developer.android.com/guide/topics/ui/controls/radiobutton.html

Thanks.

Why are the Level.FINE logging messages not showing?

The Why

java.util.logging has a root logger that defaults to Level.INFO, and a ConsoleHandler attached to it that also defaults to Level.INFO. FINE is lower than INFO, so fine messages are not displayed by default.


Solution 1

Create a logger for your whole application, e.g. from your package name or use Logger.getGlobal(), and hook your own ConsoleLogger to it. Then either ask root logger to shut up (to avoid duplicate output of higher level messages), or ask your logger to not forward logs to root.

public static final Logger applog = Logger.getGlobal();
...

// Create and set handler
Handler systemOut = new ConsoleHandler();
systemOut.setLevel( Level.ALL );
applog.addHandler( systemOut );
applog.setLevel( Level.ALL );

// Prevent logs from processed by default Console handler.
applog.setUseParentHandlers( false ); // Solution 1
Logger.getLogger("").setLevel( Level.OFF ); // Solution 2

Solution 2

Alternatively, you may lower the root logger's bar.

You can set them by code:

Logger rootLog = Logger.getLogger("");
rootLog.setLevel( Level.FINE );
rootLog.getHandlers()[0].setLevel( Level.FINE ); // Default console handler

Or with logging configuration file, if you are using it:

.level = FINE
java.util.logging.ConsoleHandler.level = FINE

By lowering the global level, you may start seeing messages from core libraries, such as from some Swing or JavaFX components. In this case you may set a Filter on the root logger to filter out messages not from your program.

C# Creating an array of arrays

I think you may be looking for Jagged Arrays, which are different from multi-dimensional arrays (as you are using in your example) in C#. Converting the arrays in your declarations to jagged arrays should make it work. However, you'll still need to use two loops to iterate over all the items in the 2D jagged array.

Python division

It has to do with the version of python that you use. Basically it adopts the C behavior: if you divide two integers, the results will be rounded down to an integer. Also keep in mind that Python does the operations from left to right, which plays a role when you typecast.

Example: Since this is a question that always pops in my head when I am doing arithmetic operations (should I convert to float and which number), an example from that aspect is presented:

>>> a = 1/2/3/4/5/4/3
>>> a
0

When we divide integers, not surprisingly it gets lower rounded.

>>> a = 1/2/3/4/5/4/float(3)
>>> a
0.0

If we typecast the last integer to float, we will still get zero, since by the time our number gets divided by the float has already become 0 because of the integer division.

>>> a = 1/2/3/float(4)/5/4/3
>>> a
0.0

Same scenario as above but shifting the float typecast a little closer to the left side.

>>> a = float(1)/2/3/4/5/4/3
>>> a
0.0006944444444444445

Finally, when we typecast the first integer to float, the result is the desired one, since beginning from the first division, i.e. the leftmost one, we use floats.

Extra 1: If you are trying to answer that to improve arithmetic evaluation, you should check this

Extra 2: Please be careful of the following scenario:

>>> a = float(1/2/3/4/5/4/3)
>>> a
0.0

Service located in another namespace

You can achieve this by deploying something at a higher layer than namespaced Services, like the service loadbalancer https://github.com/kubernetes/contrib/tree/master/service-loadbalancer. If you want to restrict it to a single namespace, use "--namespace=ns" argument (it defaults to all namespaces: https://github.com/kubernetes/contrib/blob/master/service-loadbalancer/service_loadbalancer.go#L715). This works well for L7, but is a little messy for L4.

Split string using a newline delimiter with Python

str.splitlines method should give you exactly that.

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

Example of waitpid() in use?

The syntax is

pid_t waitpid(pid_t pid, int *statusPtr, int options);

1.where pid is the process of the child it should wait.

2.statusPtr is a pointer to the location where status information for the terminating process is to be stored.

3.specifies optional actions for the waitpid function. Either of the following option flags may be specified, or they can be combined with a bitwise inclusive OR operator:

WNOHANG WUNTRACED WCONTINUED

If successful, waitpid returns the process ID of the terminated process whose status was reported. If unsuccessful, a -1 is returned.

benifits over wait

1.Waitpid can used when you have more than one child for the process and you want to wait for particular child to get its execution done before parent resumes

2.waitpid supports job control

3.it supports non blocking of the parent process

How do I show the number keyboard on an EditText in android?

Define this in your xml code

android:inputType="number"

How to add Certificate Authority file in CentOS 7

QUICK HELP 1: To add a certificate in the simple PEM or DER file formats to the list of CAs trusted on the system:

  • add it as a new file to directory /etc/pki/ca-trust/source/anchors/

  • run update-ca-trust extract

QUICK HELP 2: If your certificate is in the extended BEGIN TRUSTED file format (which may contain distrust/blacklist trust flags, or trust flags for usages other than TLS) then:

  • add it as a new file to directory /etc/pki/ca-trust/source/
  • run update-ca-trust extract

More detail infomation see man update-ca-trust

UITableViewCell, show delete button on swipe

for swift4 code, first enable editing:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

then you add delete action to the edit delegate:

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let action = UITableViewRowAction(style: .destructive, title: "Delete") { (_, index) in
        // delete model object at the index
        self.models[index.row]
        // then delete the cell
        tableView.beginUpdates()
        tableView.deleteRows(at: [index], with: .automatic)
        tableView.endUpdates()

    }
    return [action]
}

Concatenating strings in C, which method is more efficient?

The difference is unlikely to matter:

  • If your strings are small, the malloc will drown out the string concatenations.
  • If your strings are large, the time spent copying the data will drown out the differences between strcat / sprintf.

As other posters have mentioned, this is a premature optimization. Concentrate on algorithm design, and only come back to this if profiling shows it to be a performance problem.

That said... I suspect method 1 will be faster. There is some---admittedly small---overhead to parse the sprintf format-string. And strcat is more likely "inline-able".

sh: react-scripts: command not found after running npm start

I tried every answer but cleaning my npm cache worked..

steps:

  1. Clean cache =====> npm cache clean force.
  2. reinstall create-react-app =====> npm install create-react-app.
  3. npm install.
  4. npm start !!!

Trigger an event on `click` and `enter`

$('#form').keydown(function(e){
    if (e.keyCode === 13) { // If Enter key pressed
        $(this).trigger('submit');
    }
});

Java and HTTPS url connection without downloading certificate

But why don't I have to install a certificate locally for the site?

Well the code that you are using is explicitly designed to accept the certificate without doing any checks whatsoever. This is not good practice ... but if that is what you want to do, then (obviously) there is no need to install a certificate that your code is explicitly ignoring.

Shouldn't I have to install a certificate locally and load it for this program or is it downloaded behind the covers?

No, and no. See above.

Is the traffic between the client to the remote site still encrypted in transmission?

Yes it is. However, the problem is that since you have told it to trust the server's certificate without doing any checks, you don't know if you are talking to the real server, or to some other site that is pretending to be the real server. Whether this is a problem depends on the circumstances.


If we used the browser as an example, typically a browser doesn't ask the user to explicitly install a certificate for each ssl site visited.

The browser has a set of trusted root certificates pre-installed. Most times, when you visit an "https" site, the browser can verify that the site's certificate is (ultimately, via the certificate chain) secured by one of those trusted certs. If the browser doesn't recognize the cert at the start of the chain as being a trusted cert (or if the certificates are out of date or otherwise invalid / inappropriate), then it will display a warning.

Java works the same way. The JVM's keystore has a set of trusted certificates, and the same process is used to check the certificate is secured by a trusted certificate.

Does the java https client api support some type of mechanism to download certificate information automatically?

No. Allowing applications to download certificates from random places, and install them (as trusted) in the system keystore would be a security hole.

angular-cli server - how to specify default port

As far as Angular CLI: 7.1.4, there are two common ways to achieve changing the default port.

No. 1

In the angular.json, add the --port option to serve part and use ng serve to start the server.

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "demos:build",
    "port": 1337
  },
  "configurations": {
    "production": {
      "browserTarget": "demos:build:production"
    }
  }
},

No. 2

In the package.json, add the --port option to ng serve and use npm start to start the server.

  "scripts": {
    "ng": "ng",
    "start": "ng serve --port 8000",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  }, 

How can I change cols of textarea in twitter-bootstrap?

UPDATE: As of Bootstrap 3.0, the input-* classes described below for setting the width of input elements were removed. Instead use the col-* classes to set the width of input elements. Examples are provided in the documentation.


In Bootstrap 2.3, you'd use the input classes for setting the width.

<textarea class="input-mini"></textarea>
<textarea class="input-small"></textarea>
<textarea class="input-medium"></textarea>
<textarea class="input-large"></textarea>
<textarea class="input-xlarge"></textarea>
<textarea class="input-xxlarge"></textarea>?
<textarea class="input-block-level"></textarea>?

Do a find for "Control sizing" for examples in the documentation.

But for height I think you'd still use the rows attribute.

How to read value of a registry key c#

Change:

using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))

To:

 using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))

How to sum all the values in a dictionary?

In Python 2 you can avoid making a temporary copy of all the values by using the itervalues() dictionary method, which returns an iterator of the dictionary's keys:

sum(d.itervalues())

In Python 3 you can just use d.values() because that method was changed to do that (and itervalues() was removed since it was no longer needed).

To make it easier to write version independent code which always iterates over the values of the dictionary's keys, a utility function can be helpful:

import sys

def itervalues(d):
    return iter(getattr(d, ('itervalues', 'values')[sys.version_info[0]>2])())

sum(itervalues(d))

This is essentially what Benjamin Peterson's six module does.

How to compile for Windows on Linux with gcc/g++?

From: https://fedoraproject.org/wiki/MinGW/Tutorial

As of Fedora 17 it is possible to easily build (cross-compile) binaries for the win32 and win64 targets. This is realized using the mingw-w64 toolchain: http://mingw-w64.sf.net/. Using this toolchain allows you to build binaries for the following programming languages: C, C++, Objective-C, Objective-C++ and Fortran.

"Tips and tricks for using the Windows cross-compiler": https://fedoraproject.org/wiki/MinGW/Tips

Python locale error: unsupported locale setting

Run following commands

export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
sudo dpkg-reconfigure locales

It will solve this.

Make sure to match the .UTF-8 part to the actual syntax found in the output of locale -a e.g. .utf8 on some systems.

How to set an button align-right with Bootstrap?

function Continue({show, onContinue}) {
  return(<div className="row continue">
  { show ? <div className="col-11">
    <button class="btn btn-primary btn-lg float-right" onClick= {onContinue}>Continue</button>
    </div>
    : null }
  </div>);
}

How to change maven java home

Great helps above, but if you having the similar environment like I did, this is how I get it to work.

  • having a few jdk running, openjdk, oracle jdk and a few versions.
  • install apache-maven via yum, package is apache-maven-3.2.1-1.el6.noarch

Edit this file /etc/profile.d/apache-maven.sh, such as the following, note that it will affect the whole system.

$ cat /etc/profile.d/apache-maven.sh
MAVEN_HOME=/usr/share/apache-maven
M2_HOME=$MAVEN_HOME
PATH=$MAVEN_HOME/bin:$PATH
# change below to the jdk you want mvn to reference.
JAVA_HOME=/usr/java/jdk1.7.0_40/
export MAVEN_HOME
export M2_HOME
export PATH
export JAVA_HOME

How to get a list of installed android applications and pick one to run

I had a requirement to filter out the system apps which user do not really use(eg. "com.qualcomm.service", "update services", etc). Ultimately I added another condition to filter down the app list. I just checked whether the app has 'launcher intent'.

So, the resultant code looks like...

PackageManager pm = getPackageManager();
        List<ApplicationInfo> apps = pm.getInstalledApplications(PackageManager.GET_GIDS);

        for (ApplicationInfo app : apps) {
            if(pm.getLaunchIntentForPackage(app.packageName) != null) {
                // apps with launcher intent
                if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                    // updated system apps

                } else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                    // system apps

                } else {
                    // user installed apps

                }
                appsList.add(app);
            }

        }

Difference between Select Unique and Select Distinct

Unique is a keyword used in the Create Table() directive to denote that a field will contain unique data, usually used for natural keys, foreign keys etc.

For example:

Create Table Employee(   
    Emp_PKey Int Identity(1, 1) Constraint PK_Employee_Emp_PKey Primary Key,  
    Emp_SSN Numeric Not Null Unique,  
    Emp_FName varchar(16),   
    Emp_LName varchar(16) 
)

i.e. Someone's Social Security Number would likely be a unique field in your table, but not necessarily the primary key.

Distinct is used in the Select statement to notify the query that you only want the unique items returned when a field holds data that may not be unique.

Select Distinct Emp_LName
From Employee

You may have many employees with the same last name, but you only want each different last name.

Obviously if the field you are querying holds unique data, then the Distinct keyword becomes superfluous.

Get type of a generic parameter in Java with reflection

This is impossible because generics in Java are only considered at compile time. Thus, the Java generics are just some kind of pre-processor. However you can get the actual class of the members of the list.

How to fill a datatable with List<T>

I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable and the underlying data was a IEnumerable and the properties couldn't be enumerated. This did the trick:

// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
    List<IDataRecord> list = data.Cast<IDataRecord>().ToList();

    PropertyDescriptorCollection props = null;
    DataTable table = new DataTable();
    if (list != null && list.Count > 0)
    {
        props = TypeDescriptor.GetProperties(list[0]);
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
    }
    if (props != null)
    {
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item) ?? DBNull.Value;
            }
            table.Rows.Add(values);
        }
    }
    return table;
}

Can I use a binary literal in C or C++?

I extended the good answer given by @renato-chandelier by ensuring the support of:

  • _NIBBLE_(…) – 4 bits, 1 nibble as argument
  • _BYTE_(…) – 8 bits, 2 nibbles as arguments
  • _SLAB_(…) – 12 bits, 3 nibbles as arguments
  • _WORD_(…) – 16 bits, 4 nibbles as arguments
  • _QUINTIBBLE_(…) – 20 bits, 5 nibbles as arguments
  • _DSLAB_(…) – 24 bits, 6 nibbles as arguments
  • _SEPTIBBLE_(…) – 28 bits, 7 nibbles as arguments
  • _DWORD_(…) – 32 bits, 8 nibbles as arguments

I am actually not so sure about the terms “quintibble” and “septibble”. If anyone knows any alternative please let me know.

Here is the macro rewritten:

#define __CAT__(A, B) A##B
#define _CAT_(A, B) __CAT__(A, B)

#define __HEX_0000 0
#define __HEX_0001 1
#define __HEX_0010 2
#define __HEX_0011 3
#define __HEX_0100 4
#define __HEX_0101 5
#define __HEX_0110 6
#define __HEX_0111 7
#define __HEX_1000 8
#define __HEX_1001 9
#define __HEX_1010 a
#define __HEX_1011 b
#define __HEX_1100 c
#define __HEX_1101 d
#define __HEX_1110 e
#define __HEX_1111 f

#define _NIBBLE_(N1) _CAT_(0x, _CAT_(__HEX_, N1))
#define _BYTE_(N1, N2) _CAT_(_NIBBLE_(N1), _CAT_(__HEX_, N2))
#define _SLAB_(N1, N2, N3) _CAT_(_BYTE_(N1, N2), _CAT_(__HEX_, N3))
#define _WORD_(N1, N2, N3, N4) _CAT_(_SLAB_(N1, N2, N3), _CAT_(__HEX_, N4))
#define _QUINTIBBLE_(N1, N2, N3, N4, N5) _CAT_(_WORD_(N1, N2, N3, N4), _CAT_(__HEX_, N5))
#define _DSLAB_(N1, N2, N3, N4, N5, N6) _CAT_(_QUINTIBBLE_(N1, N2, N3, N4, N5), _CAT_(__HEX_, N6))
#define _SEPTIBBLE_(N1, N2, N3, N4, N5, N6, N7) _CAT_(_DSLAB_(N1, N2, N3, N4, N5, N6), _CAT_(__HEX_, N7))
#define _DWORD_(N1, N2, N3, N4, N5, N6, N7, N8) _CAT_(_SEPTIBBLE_(N1, N2, N3, N4, N5, N6, N7), _CAT_(__HEX_, N8))

And here is Renato's using example:

char b = _BYTE_(0100, 0001); /* equivalent to b = 65; or b = 'A'; or b = 0x41; */
unsigned int w = _WORD_(1101, 1111, 0100, 0011); /* equivalent to w = 57155; or w = 0xdf43; */
unsigned long int dw = _DWORD_(1101, 1111, 0100, 0011, 1111, 1101, 0010, 1000); /* Equivalent to dw = 3745774888; or dw = 0xdf43fd28; */

Why use the 'ref' keyword when passing an object?

Since TestRef is a class (which are reference objects), you can change the contents inside t without passing it as a ref. However, if you pass t as a ref, TestRef can change what the original t refers to. i.e. make it point to a different object.

How do I use CREATE OR REPLACE?

Following script should do the trick on Oracle:

BEGIN
  EXECUTE IMMEDIATE 'drop TABLE tablename';
EXCEPTION
  WHEN OTHERS THEN
    IF sqlcode != -0942 THEN RAISE; 
    END IF;
END;

mysql update multiple columns with same now()

You can put the following code on the default value of the timestamp column: CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, so on update the two columns take the same value.

Resolving IP Address from hostname with PowerShell

If you know part of the subnet (i.e. 10.3 in this example), then this will grab any addresses that are in the given subnet:

PS C:\> [System.Net.Dns]::GetHostAddresses("MyPC") | foreach { $_.IPAddressToString | findstr "10.3."}

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

This error is generally caused by one of your Chrome extensions.

I recommend installing this One-Click Extension Disabler, I use it with the keyboard shortcut COMMAND (?) + SHIFT (?) + D — to quickly disable/enable all my extensions.

Once the extensions are disabled this error message should go away.

Peace! ??

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):

import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"

evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)

in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.

Laravel Redirect Back with() Message

Alternative approach would be

Controller

use Session;
       
Session::flash('message', "Special message goes here");
return Redirect::back();

View

@if (Session::has('message'))
   <div class="alert alert-info">{{ Session::get('message') }}</div>
@endif

How do I use extern to share variables between source files?

Extern is the keyword you use to declare that the variable itself resides in another translation unit.

So you can decide to use a variable in a translation unit and then access it from another one, then in the second one you declare it as extern and the symbol will be resolved by the linker.

If you don't declare it as extern you'll get 2 variables named the same but not related at all, and an error of multiple definitions of the variable.

file_get_contents() Breaks Up UTF-8 Characters

I am working with 35000 lines of data.

$f=fopen("veri1.txt","r");
$i=0;
while(!feof($f)){
    $i++;
    $line=mb_convert_encoding(fgets($f), 'HTML-ENTITIES', "UTF-8");
    echo $line;
}

This code convert my strange characters into normal.

How to save a new sheet in an existing excel file, using Pandas?

Thank you. I believe that a complete example could be good for anyone else who have the same issue:

import pandas as pd
import numpy as np

path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"

x1 = np.random.randn(100, 2)
df1 = pd.DataFrame(x1)

x2 = np.random.randn(100, 2)
df2 = pd.DataFrame(x2)

writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
df1.to_excel(writer, sheet_name = 'x1')
df2.to_excel(writer, sheet_name = 'x2')
writer.save()
writer.close()

Here I generate an excel file, from my understanding it does not really matter whether it is generated via the "xslxwriter" or the "openpyxl" engine.

When I want to write without loosing the original data then

import pandas as pd
import numpy as np
from openpyxl import load_workbook

path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"

book = load_workbook(path)
writer = pd.ExcelWriter(path, engine = 'openpyxl')
writer.book = book

x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)

x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)

df3.to_excel(writer, sheet_name = 'x3')
df4.to_excel(writer, sheet_name = 'x4')
writer.save()
writer.close()

this code do the job!

Read connection string from web.config

You need to add a reference to System.Configuration and then use:

System.Configuration.ConfigurationManager.
    ConnectionStrings["connectionStringName"].ConnectionString;

Can't compile C program on a Mac after upgrade to Mojave

I was having this issue and nothing worked. I ran xcode-select --install and also installed /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg.

BACKGROUND

Since I was having issues with App Store on a new laptop, I was forced to download the Xcode Beta installer from the Apple website to install Xcode outside App Store. So I only had Xcode Beta installed.

SOLUTION

This, (I think), was making clang to not find the SDKROOT directory /Applications/Xcode.app/...., because there is no Beta in the path, or maybe Xcode Beta simply doesn't install it (I don't know). To fix the issue, I had to remove Xcode Beta and resolve the App Store issue to install the release version.

tldr;

If you have Xcode Beta, try cleaning up everything and installing the release version before trying out the solutions that are working for other people.

Newline in markdown table?

Use <br/> . For example:

Change log, upgrade version

Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`

URL: https://github.com/donhuvy/lsb/wiki

Assign keyboard shortcut to run procedure

Here is how to assign a keyboard shortcut to a custom macro in Word 2013. The scenario is you created a macro named "fred" and you want to execute the macro by typing Ctrl+f.

  1. Click on File, Options.
  2. Click on Customize Ribbon (from my perspective this is the non-intuitive step).
  3. Click "Keyboard shortcuts: Customize" button.
  4. In the Categories listbox scroll down to the buttom and select Macros.
  5. The Macros list box should now show the list of custom macros. Select "fred".
  6. Click the "Press new shortcut key" textbox to make it active.
  7. Type Ctrl+f. This should appear in the textbox.
  8. Look at the "Current keys" listbox. In this case it shows "Currently assigned to NavPaneSearch".
  9. If you don't mind overriding that default, click the "Assign" button on the lower-left to assign "Ctrl+f: to run your "fred" macro.

By default the assignment is saved in the Normal.dotm document template. If this keyboard assignment is unique to this document then you may wish to change the "Save changes in" dropdown to your document name.

Local dependency in package.json

Here in 2020, working on a Windows 10, I tried with

"dependencies": {
    "some-local-lib": "file:../../folderY/some-local-lib" 
    ...
}

Then doing a npm install. The result is that a shortcut to the folder is created in node-modules. This doesn't work. You need a hard link - which windows support, but you have to do something extra in windows to create a hard symlink.

Since I don't really want a hard link, I tried using an url instead:

"dependencies": {
    "some-local-lib": "file:///D:\\folderX\\folderY\\some-local-lib.tar" 
     ....
}

And this works nicely.
The tar (you have to tar the stuff in the library's build / dist folder) gets extracted to a real folder in node-modules, and you can import like everything else.
Obviously the tar part is a bit annoying, but since 'some-local-lib' is a library (which has to be build anyway), I prefer this solution to creating a hard link or installing a local npm.

How do I solve the "server DNS address could not be found" error on Windows 10?

Steps to manually configure DNS:

  1. You can access Network and Sharing center by right clicking on the Network icon on the taskbar.

  2. Now choose adapter settings from the side menu.

  3. This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.

  4. In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.

  5. Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.

    Select ‘use the following DNS address’ option. Now fill the following fields as given here.

    Preferred DNS server: 208.67.222.222

    Alternate DNS server : 208.67.220.220

    This is an available Open DNS address. You may also use google DNS server addresses.

    After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.

You have to add this DNS server address in the router configuration also (by referring the router manual for more information).

Refer : for above method & alternative

If none of this works, then open command prompt(Run as Administrator) and run these:

ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit

Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).

Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue

Read int values from a text file in C

How about this?

fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2); 

In this case spaces in fscanf match multiple occurrences of any whitespace until the next token in found.

What is the minimum length of a valid international phone number?

As per different sources, I think the minimum length in E-164 format depends on country to country. For eg:

  • For Israel: The minimum phone number length (excluding the country code) is 8 digits. - Official Source (Country Code 972)
  • For Sweden : The minimum number length (excluding the country code) is 7 digits. - Official Source? (country code 46)

  • For Solomon Islands its 5 for fixed line phones. - Source (country code 677)

... and so on. So including country code, the minimum length is 9 digits for Sweden and 11 for Israel and 8 for Solomon Islands.

Edit (Clean Solution): Actually, Instead of validating an international phone number by having different checks like length etc, you can use the Google's libphonenumber library. It can validate a phone number in E164 format directly. It will take into account everything and you don't even need to give the country if the number is in valid E164 format. Its pretty good! Taking an example:

String phoneNumberE164Format = "+14167129018"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    PhoneNumber phoneNumberProto = phoneUtil.parse(phoneNumberE164Format, null);
    boolean isValid = phoneUtil.isValidNumber(phoneNumberProto); // returns true if valid
    if (isValid) {
        // Actions to perform if the number is valid
    } else {
        // Do necessary actions if its not valid 
    }
} catch (NumberParseException e) {
    System.err.println("NumberParseException was thrown: " + e.toString());
}

If you know the country for which you are validating the numbers, you don;t even need the E164 format and can specify the country in .parse function instead of passing null.

Received an invalid column length from the bcp client for colid 6

I just stumbled upon this and using @b_stil's snippet, I was able to figure the culprit column. And on futher investigation, I figured i needed to trim the column just like @Liji Chandran suggested but I was using IExcelDataReader and I couldn't figure out an easy way to validate and trim each of my 160 columns.

Then I stumbled upon this class, (ValidatingDataReader) class from CSVReader.

Interesting thing about this class is that it gives you the source and destination columns data length, the culprit row and even the column value that's causing the error.

All I did was just trim all (nvarchar, varchar, char and nchar) columns.

I just changed my GetValue method to this:

 object IDataRecord.GetValue(int i)
    {
        object columnValue = reader.GetValue(i);

        if (i > -1 && i < lookup.Length)
        {
            DataRow columnDef = lookup[i];
            if
            (
                (
                    (string)columnDef["DataTypeName"] == "varchar" ||
                    (string)columnDef["DataTypeName"] == "nvarchar" ||
                    (string)columnDef["DataTypeName"] == "char" ||
                    (string)columnDef["DataTypeName"] == "nchar"
                ) &&
                (
                    columnValue != null &&
                    columnValue != DBNull.Value
                )
            )
            {
                string stringValue = columnValue.ToString().Trim();

                columnValue = stringValue;


                if (stringValue.Length > (int)columnDef["ColumnSize"])
                {
                    string message =
                        "Column value \"" + stringValue.Replace("\"", "\\\"") + "\"" +
                        " with length " + stringValue.Length.ToString("###,##0") +
                        " from source column " + (this as IDataRecord).GetName(i) +
                        " in record " + currentRecord.ToString("###,##0") +
                        " does not fit in destination column " + columnDef["ColumnName"] +
                        " with length " + ((int)columnDef["ColumnSize"]).ToString("###,##0") +
                        " in table " + tableName +
                        " in database " + databaseName +
                        " on server " + serverName + ".";

                    if (ColumnException == null)
                    {
                        throw new Exception(message);
                    }
                    else
                    {
                        ColumnExceptionEventArgs args = new ColumnExceptionEventArgs();

                        args.DataTypeName = (string)columnDef["DataTypeName"];
                        args.DataType = Type.GetType((string)columnDef["DataType"]);
                        args.Value = columnValue;
                        args.SourceIndex = i;
                        args.SourceColumn = reader.GetName(i);
                        args.DestIndex = (int)columnDef["ColumnOrdinal"];
                        args.DestColumn = (string)columnDef["ColumnName"];
                        args.ColumnSize = (int)columnDef["ColumnSize"];
                        args.RecordIndex = currentRecord;
                        args.TableName = tableName;
                        args.DatabaseName = databaseName;
                        args.ServerName = serverName;
                        args.Message = message;

                        ColumnException(args);

                        columnValue = args.Value;
                    }
                }



            }
        }

        return columnValue;
    }

Hope this helps someone

Laravel Controller Subfolder routing

I am using Laravel 4.2. Here how I do it:
I have a directory structure like this one:
app
--controllers
----admin
------AdminController.php

After I have created the controller I've put in the composer.json the path to the new admin directory:

"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/controllers/admin",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
}, 

Next I have run

composer dump-autoload

and then

php artisan dump-autoload

Then in the routes.php I have the controller included like this:

Route::controller('admin', 'AdminController');

And everything works fine.

How to create and handle composite primary key in JPA

The MyKey class (@Embeddable) should not have any relationships like @ManyToOne

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

HTML5 tag for horizontal line break

Instead of using <hr>, you can one of the border of the enclosing block and display it as a horizontal line.

Here is a sample code:

The HTML:

<div class="title_block">
    <h3>This is a header.</h3>
</div>
<p>Here is some sample paragraph text.<br>
This demonstrates that a horizontal line goes between the title and the paragraph.</p>

The CSS:

.title_block {
    border-bottom: 1px solid #ddd;
    padding-bottom: 5px;
    margin-bottom: 5px;
}

How to detect the character encoding of a text file?

If you want to pursue a "simple" solution, you might find this class I put together useful:

http://www.architectshack.com/TextFileEncodingDetector.ashx

It does the BOM detection automatically first, and then tries to differentiate between Unicode encodings without BOM, vs some other default encoding (generally Windows-1252, incorrectly labelled as Encoding.ASCII in .Net).

As noted above, a "heavier" solution involving NCharDet or MLang may be more appropriate, and as I note on the overview page of this class, the best is to provide some form of interactivity with the user if at all possible, because there simply is no 100% detection rate possible!

Snippet in case the site is offline:

using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace KlerksSoft
{
    public static class TextFileEncodingDetector
    {
        /*
         * Simple class to handle text file encoding woes (in a primarily English-speaking tech 
         *      world).
         * 
         *  - This code is fully managed, no shady calls to MLang (the unmanaged codepage
         *      detection library originally developed for Internet Explorer).
         * 
         *  - This class does NOT try to detect arbitrary codepages/charsets, it really only
         *      aims to differentiate between some of the most common variants of Unicode 
         *      encoding, and a "default" (western / ascii-based) encoding alternative provided
         *      by the caller.
         *      
         *  - As there is no "Reliable" way to distinguish between UTF-8 (without BOM) and 
         *      Windows-1252 (in .Net, also incorrectly called "ASCII") encodings, we use a 
         *      heuristic - so the more of the file we can sample the better the guess. If you 
         *      are going to read the whole file into memory at some point, then best to pass 
         *      in the whole byte byte array directly. Otherwise, decide how to trade off 
         *      reliability against performance / memory usage.
         *      
         *  - The UTF-8 detection heuristic only works for western text, as it relies on 
         *      the presence of UTF-8 encoded accented and other characters found in the upper 
         *      ranges of the Latin-1 and (particularly) Windows-1252 codepages.
         *  
         *  - For more general detection routines, see existing projects / resources:
         *    - MLang - Microsoft library originally for IE6, available in Windows XP and later APIs now (I think?)
         *      - MLang .Net bindings: http://www.codeproject.com/KB/recipes/DetectEncoding.aspx
         *    - CharDet - Mozilla browser's detection routines
         *      - Ported to Java then .Net: http://www.conceptdevelopment.net/Localization/NCharDet/
         *      - Ported straight to .Net: http://code.google.com/p/chardetsharp/source/browse
         *  
         * Copyright Tao Klerks, 2010-2012, [email protected]
         * Licensed under the modified BSD license:
         * 
Redistribution and use in source and binary forms, with or without modification, are 
permitted provided that the following conditions are met:
 - Redistributions of source code must retain the above copyright notice, this list of 
conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright notice, this list 
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
 - The name of the author may not be used to endorse or promote products derived from 
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY 
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
OF SUCH DAMAGE.
         * 
         * CHANGELOG:
         *  - 2012-02-03: 
         *    - Simpler methods, removing the silly "DefaultEncoding" parameter (with "??" operator, saves no typing)
         *    - More complete methods
         *      - Optionally return indication of whether BOM was found in "Detect" methods
         *      - Provide straight-to-string method for byte arrays (GetStringFromByteArray)
         */

        const long _defaultHeuristicSampleSize = 0x10000; //completely arbitrary - inappropriate for high numbers of files / high speed requirements

        public static Encoding DetectTextFileEncoding(string InputFilename)
        {
            using (FileStream textfileStream = File.OpenRead(InputFilename))
            {
                return DetectTextFileEncoding(textfileStream, _defaultHeuristicSampleSize);
            }
        }

        public static Encoding DetectTextFileEncoding(FileStream InputFileStream, long HeuristicSampleSize)
        {
            bool uselessBool = false;
            return DetectTextFileEncoding(InputFileStream, _defaultHeuristicSampleSize, out uselessBool);
        }

        public static Encoding DetectTextFileEncoding(FileStream InputFileStream, long HeuristicSampleSize, out bool HasBOM)
        {
            if (InputFileStream == null)
                throw new ArgumentNullException("Must provide a valid Filestream!", "InputFileStream");

            if (!InputFileStream.CanRead)
                throw new ArgumentException("Provided file stream is not readable!", "InputFileStream");

            if (!InputFileStream.CanSeek)
                throw new ArgumentException("Provided file stream cannot seek!", "InputFileStream");

            Encoding encodingFound = null;

            long originalPos = InputFileStream.Position;

            InputFileStream.Position = 0;


            //First read only what we need for BOM detection
            byte[] bomBytes = new byte[InputFileStream.Length > 4 ? 4 : InputFileStream.Length];
            InputFileStream.Read(bomBytes, 0, bomBytes.Length);

            encodingFound = DetectBOMBytes(bomBytes);

            if (encodingFound != null)
            {
                InputFileStream.Position = originalPos;
                HasBOM = true;
                return encodingFound;
            }


            //BOM Detection failed, going for heuristics now.
            //  create sample byte array and populate it
            byte[] sampleBytes = new byte[HeuristicSampleSize > InputFileStream.Length ? InputFileStream.Length : HeuristicSampleSize];
            Array.Copy(bomBytes, sampleBytes, bomBytes.Length);
            if (InputFileStream.Length > bomBytes.Length)
                InputFileStream.Read(sampleBytes, bomBytes.Length, sampleBytes.Length - bomBytes.Length);
            InputFileStream.Position = originalPos;

            //test byte array content
            encodingFound = DetectUnicodeInByteSampleByHeuristics(sampleBytes);

            HasBOM = false;
            return encodingFound;
        }

        public static Encoding DetectTextByteArrayEncoding(byte[] TextData)
        {
            bool uselessBool = false;
            return DetectTextByteArrayEncoding(TextData, out uselessBool);
        }

        public static Encoding DetectTextByteArrayEncoding(byte[] TextData, out bool HasBOM)
        {
            if (TextData == null)
                throw new ArgumentNullException("Must provide a valid text data byte array!", "TextData");

            Encoding encodingFound = null;

            encodingFound = DetectBOMBytes(TextData);

            if (encodingFound != null)
            {
                HasBOM = true;
                return encodingFound;
            }
            else
            {
                //test byte array content
                encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData);

                HasBOM = false;
                return encodingFound;
            }
        }

        public static string GetStringFromByteArray(byte[] TextData, Encoding DefaultEncoding)
        {
            return GetStringFromByteArray(TextData, DefaultEncoding, _defaultHeuristicSampleSize);
        }

        public static string GetStringFromByteArray(byte[] TextData, Encoding DefaultEncoding, long MaxHeuristicSampleSize)
        {
            if (TextData == null)
                throw new ArgumentNullException("Must provide a valid text data byte array!", "TextData");

            Encoding encodingFound = null;

            encodingFound = DetectBOMBytes(TextData);

            if (encodingFound != null)
            {
                //For some reason, the default encodings don't detect/swallow their own preambles!!
                return encodingFound.GetString(TextData, encodingFound.GetPreamble().Length, TextData.Length - encodingFound.GetPreamble().Length);
            }
            else
            {
                byte[] heuristicSample = null;
                if (TextData.Length > MaxHeuristicSampleSize)
                {
                    heuristicSample = new byte[MaxHeuristicSampleSize];
                    Array.Copy(TextData, heuristicSample, MaxHeuristicSampleSize);
                }
                else
                {
                    heuristicSample = TextData;
                }

                encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData) ?? DefaultEncoding;
                return encodingFound.GetString(TextData);
            }
        }


        public static Encoding DetectBOMBytes(byte[] BOMBytes)
        {
            if (BOMBytes == null)
                throw new ArgumentNullException("Must provide a valid BOM byte array!", "BOMBytes");

            if (BOMBytes.Length < 2)
                return null;

            if (BOMBytes[0] == 0xff 
                && BOMBytes[1] == 0xfe 
                && (BOMBytes.Length < 4 
                    || BOMBytes[2] != 0 
                    || BOMBytes[3] != 0
                    )
                )
                return Encoding.Unicode;

            if (BOMBytes[0] == 0xfe 
                && BOMBytes[1] == 0xff
                )
                return Encoding.BigEndianUnicode;

            if (BOMBytes.Length < 3)
                return null;

            if (BOMBytes[0] == 0xef && BOMBytes[1] == 0xbb && BOMBytes[2] == 0xbf)
                return Encoding.UTF8;

            if (BOMBytes[0] == 0x2b && BOMBytes[1] == 0x2f && BOMBytes[2] == 0x76)
                return Encoding.UTF7;

            if (BOMBytes.Length < 4)
                return null;

            if (BOMBytes[0] == 0xff && BOMBytes[1] == 0xfe && BOMBytes[2] == 0 && BOMBytes[3] == 0)
                return Encoding.UTF32;

            if (BOMBytes[0] == 0 && BOMBytes[1] == 0 && BOMBytes[2] == 0xfe && BOMBytes[3] == 0xff)
                return Encoding.GetEncoding(12001);

            return null;
        }

        public static Encoding DetectUnicodeInByteSampleByHeuristics(byte[] SampleBytes)
        {
            long oddBinaryNullsInSample = 0;
            long evenBinaryNullsInSample = 0;
            long suspiciousUTF8SequenceCount = 0;
            long suspiciousUTF8BytesTotal = 0;
            long likelyUSASCIIBytesInSample = 0;

            //Cycle through, keeping count of binary null positions, possible UTF-8 
            //  sequences from upper ranges of Windows-1252, and probable US-ASCII 
            //  character counts.

            long currentPos = 0;
            int skipUTF8Bytes = 0;

            while (currentPos < SampleBytes.Length)
            {
                //binary null distribution
                if (SampleBytes[currentPos] == 0)
                {
                    if (currentPos % 2 == 0)
                        evenBinaryNullsInSample++;
                    else
                        oddBinaryNullsInSample++;
                }

                //likely US-ASCII characters
                if (IsCommonUSASCIIByte(SampleBytes[currentPos]))
                    likelyUSASCIIBytesInSample++;

                //suspicious sequences (look like UTF-8)
                if (skipUTF8Bytes == 0)
                {
                    int lengthFound = DetectSuspiciousUTF8SequenceLength(SampleBytes, currentPos);

                    if (lengthFound > 0)
                    {
                        suspiciousUTF8SequenceCount++;
                        suspiciousUTF8BytesTotal += lengthFound;
                        skipUTF8Bytes = lengthFound - 1;
                    }
                }
                else
                {
                    skipUTF8Bytes--;
                }

                currentPos++;
            }

            //1: UTF-16 LE - in english / european environments, this is usually characterized by a 
            //  high proportion of odd binary nulls (starting at 0), with (as this is text) a low 
            //  proportion of even binary nulls.
            //  The thresholds here used (less than 20% nulls where you expect non-nulls, and more than
            //  60% nulls where you do expect nulls) are completely arbitrary.

            if (((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2 
                && ((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
                )
                return Encoding.Unicode;


            //2: UTF-16 BE - in english / european environments, this is usually characterized by a 
            //  high proportion of even binary nulls (starting at 0), with (as this is text) a low 
            //  proportion of odd binary nulls.
            //  The thresholds here used (less than 20% nulls where you expect non-nulls, and more than
            //  60% nulls where you do expect nulls) are completely arbitrary.

            if (((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2 
                && ((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
                )
                return Encoding.BigEndianUnicode;


            //3: UTF-8 - Martin Dürst outlines a method for detecting whether something CAN be UTF-8 content 
            //  using regexp, in his w3c.org unicode FAQ entry: 
            //  http://www.w3.org/International/questions/qa-forms-utf-8
            //  adapted here for C#.
            string potentiallyMangledString = Encoding.ASCII.GetString(SampleBytes);
            Regex UTF8Validator = new Regex(@"\A(" 
                + @"[\x09\x0A\x0D\x20-\x7E]"
                + @"|[\xC2-\xDF][\x80-\xBF]"
                + @"|\xE0[\xA0-\xBF][\x80-\xBF]"
                + @"|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}"
                + @"|\xED[\x80-\x9F][\x80-\xBF]"
                + @"|\xF0[\x90-\xBF][\x80-\xBF]{2}"
                + @"|[\xF1-\xF3][\x80-\xBF]{3}"
                + @"|\xF4[\x80-\x8F][\x80-\xBF]{2}"
                + @")*\z");
            if (UTF8Validator.IsMatch(potentiallyMangledString))
            {
                //Unfortunately, just the fact that it CAN be UTF-8 doesn't tell you much about probabilities.
                //If all the characters are in the 0-127 range, no harm done, most western charsets are same as UTF-8 in these ranges.
                //If some of the characters were in the upper range (western accented characters), however, they would likely be mangled to 2-byte by the UTF-8 encoding process.
                // So, we need to play stats.

                // The "Random" likelihood of any pair of randomly generated characters being one 
                //   of these "suspicious" character sequences is:
                //     128 / (256 * 256) = 0.2%.
                //
                // In western text data, that is SIGNIFICANTLY reduced - most text data stays in the <127 
                //   character range, so we assume that more than 1 in 500,000 of these character 
                //   sequences indicates UTF-8. The number 500,000 is completely arbitrary - so sue me.
                //
                // We can only assume these character sequences will be rare if we ALSO assume that this
                //   IS in fact western text - in which case the bulk of the UTF-8 encoded data (that is 
                //   not already suspicious sequences) should be plain US-ASCII bytes. This, I 
                //   arbitrarily decided, should be 80% (a random distribution, eg binary data, would yield 
                //   approx 40%, so the chances of hitting this threshold by accident in random data are 
                //   VERY low). 

                if ((suspiciousUTF8SequenceCount * 500000.0 / SampleBytes.Length >= 1) //suspicious sequences
                    && (
                           //all suspicious, so cannot evaluate proportion of US-Ascii
                           SampleBytes.Length - suspiciousUTF8BytesTotal == 0 
                           ||
                           likelyUSASCIIBytesInSample * 1.0 / (SampleBytes.Length - suspiciousUTF8BytesTotal) >= 0.8
                       )
                    )
                    return Encoding.UTF8;
            }

            return null;
        }

        private static bool IsCommonUSASCIIByte(byte testByte)
        {
            if (testByte == 0x0A //lf
                || testByte == 0x0D //cr
                || testByte == 0x09 //tab
                || (testByte >= 0x20 && testByte <= 0x2F) //common punctuation
                || (testByte >= 0x30 && testByte <= 0x39) //digits
                || (testByte >= 0x3A && testByte <= 0x40) //common punctuation
                || (testByte >= 0x41 && testByte <= 0x5A) //capital letters
                || (testByte >= 0x5B && testByte <= 0x60) //common punctuation
                || (testByte >= 0x61 && testByte <= 0x7A) //lowercase letters
                || (testByte >= 0x7B && testByte <= 0x7E) //common punctuation
                )
                return true;
            else
                return false;
        }

        private static int DetectSuspiciousUTF8SequenceLength(byte[] SampleBytes, long currentPos)
        {
            int lengthFound = 0;

            if (SampleBytes.Length >= currentPos + 1 
                && SampleBytes[currentPos] == 0xC2
                )
            {
                if (SampleBytes[currentPos + 1] == 0x81 
                    || SampleBytes[currentPos + 1] == 0x8D 
                    || SampleBytes[currentPos + 1] == 0x8F
                    )
                    lengthFound = 2;
                else if (SampleBytes[currentPos + 1] == 0x90 
                    || SampleBytes[currentPos + 1] == 0x9D
                    )
                    lengthFound = 2;
                else if (SampleBytes[currentPos + 1] >= 0xA0 
                    && SampleBytes[currentPos + 1] <= 0xBF
                    )
                    lengthFound = 2;
            }
            else if (SampleBytes.Length >= currentPos + 1 
                && SampleBytes[currentPos] == 0xC3
                )
            {
                if (SampleBytes[currentPos + 1] >= 0x80 
                    && SampleBytes[currentPos + 1] <= 0xBF
                    )
                    lengthFound = 2;
            }
            else if (SampleBytes.Length >= currentPos + 1 
                && SampleBytes[currentPos] == 0xC5
                )
            {
                if (SampleBytes[currentPos + 1] == 0x92 
                    || SampleBytes[currentPos + 1] == 0x93
                    )
                    lengthFound = 2;
                else if (SampleBytes[currentPos + 1] == 0xA0 
                    || SampleBytes[currentPos + 1] == 0xA1
                    )
                    lengthFound = 2;
                else if (SampleBytes[currentPos + 1] == 0xB8 
                    || SampleBytes[currentPos + 1] == 0xBD 
                    || SampleBytes[currentPos + 1] == 0xBE
                    )
                    lengthFound = 2;
            }
            else if (SampleBytes.Length >= currentPos + 1 
                && SampleBytes[currentPos] == 0xC6
                )
            {
                if (SampleBytes[currentPos + 1] == 0x92)
                    lengthFound = 2;
            }
            else if (SampleBytes.Length >= currentPos + 1 
                && SampleBytes[currentPos] == 0xCB
                )
            {
                if (SampleBytes[currentPos + 1] == 0x86 
                    || SampleBytes[currentPos + 1] == 0x9C
                    )
                    lengthFound = 2;
            }
            else if (SampleBytes.Length >= currentPos + 2 
                && SampleBytes[currentPos] == 0xE2
                )
            {
                if (SampleBytes[currentPos + 1] == 0x80)
                {
                    if (SampleBytes[currentPos + 2] == 0x93 
                        || SampleBytes[currentPos + 2] == 0x94
                        )
                        lengthFound = 3;
                    if (SampleBytes[currentPos + 2] == 0x98 
                        || SampleBytes[currentPos + 2] == 0x99 
                        || SampleBytes[currentPos + 2] == 0x9A
                        )
                        lengthFound = 3;
                    if (SampleBytes[currentPos + 2] == 0x9C 
                        || SampleBytes[currentPos + 2] == 0x9D 
                        || SampleBytes[currentPos + 2] == 0x9E
                        )
                        lengthFound = 3;
                    if (SampleBytes[currentPos + 2] == 0xA0 
                        || SampleBytes[currentPos + 2] == 0xA1 
                        || SampleBytes[currentPos + 2] == 0xA2
                        )
                        lengthFound = 3;
                    if (SampleBytes[currentPos + 2] == 0xA6)
                        lengthFound = 3;
                    if (SampleBytes[currentPos + 2] == 0xB0)
                        lengthFound = 3;
                    if (SampleBytes[currentPos + 2] == 0xB9 
                        || SampleBytes[currentPos + 2] == 0xBA
                        )
                        lengthFound = 3;
                }
                else if (SampleBytes[currentPos + 1] == 0x82 
                    && SampleBytes[currentPos + 2] == 0xAC
                    )
                    lengthFound = 3;
                else if (SampleBytes[currentPos + 1] == 0x84 
                    && SampleBytes[currentPos + 2] == 0xA2
                    )
                    lengthFound = 3;
            }

            return lengthFound;
        }

    }
}

<img>: Unsafe value used in a resource URL context

The most elegant way to fix this: use pipe. Here is example (my blog). So you can then simply use url | safe pipe to bypass the security.

<iframe [src]="url | safe"></iframe>

Refer to the documentation on npm for details: https://www.npmjs.com/package/safe-pipe

Plotting multiple lines, in different colors, with pandas dataframe

If you have seaborn installed, an easier method that does not require you to perform pivot:

import seaborn as sns

sns.lineplot(data=df, x='x', y='y', hue='color')

pass post data with window.location.href

it's as simple as this

$.post({url: "som_page.php", 
    data: { data1: value1, data2: value2 }
    ).done(function( data ) { 
        $( "body" ).html(data);
    });
});

I had to solve this to make a screen lock of my application where I had to pass sensitive data as user and the url where he was working. Then create a function that executes this code

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

There's some sort of bogus character at the end of that source. Try deleting the last line and adding it back.

I can't figure out exactly what's there, yet ...

edit — I think it's a zero-width space, Unicode 200B. Seems pretty weird and I can't be sure of course that it's not a Stackoverflow artifact, but when I copy/paste that last function including the complete last line into the Chrome console, I get your error.

A notorious source of such characters are websites like jsfiddle. I'm not saying that there's anything wrong with them — it's just a side-effect of something, maybe the use of content-editable input widgets.

If you suspect you've got a case of this ailment, and you're on MacOS or Linux/Unix, the od command line tool can show you (albeit in a fairly ugly way) the numeric values in the characters of the source code file. Some IDEs and editors can show "funny" characters as well. Note that such characters aren't always a problem. It's perfectly OK (in most reasonable programming languages, anyway) for there to be embedded Unicode characters in string constants, for example. The problems start happening when the language parser encounters the characters when it doesn't expect them.

How can I get log4j to delete old rotating log files?

There is no default value to control deleting old log files created by DailyRollingFileAppender. But you can write your own custom Appender that deletes old log files in much the same way as setting maxBackupIndex does for RollingFileAppender.

Simple instructions found here

From 1:

If you are trying to use the Apache Log4J DailyRollingFileAppender for a daily log file, you may need to want to specify the maximum number of files which should be kept. Just like rolling RollingFileAppender supports maxBackupIndex. But the current version of Log4j (Apache log4j 1.2.16) does not provide any mechanism to delete old log files if you are using DailyRollingFileAppender. I tried to make small modifications in the original version of DailyRollingFileAppender to add maxBackupIndex property. So, it would be possible to clean up old log files which may not be required for future usage.

Change default timeout for mocha

Adding this for completeness. If you (like me) use a script in your package.json file, just add the --timeout option to mocha:

"scripts": {
  "test": "mocha 'test/**/*.js' --timeout 10000",
  "test-debug": "mocha --debug 'test/**/*.js' --timeout 10000"
},

Then you can run npm run test to run your test suite with the timeout set to 10,000 milliseconds.

Make the size of a heatmap bigger with seaborn

I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:

f, ax = plt.subplots(figsize=(16, 12))

at the meantime until you get a matched size colobar. This worked for me.

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

Help -> check for updates upon Eclipse update solved the issue

Right to Left support for Twitter Bootstrap 3

finally, I can find a new version for the right to left bootstrap. share here for use by all:

bootstrap-3-3-7-rtl and RTL Bootstrap 4.0.0-alpha.6.1

GitHub link:

https://github.com/parsmizban/RTL-Bootstrap

thank you parsmizban.com for creating and share.

Set a request header in JavaScript

@gnarf answer is right . wanted to add more information .

Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Terminate these steps if header is a case-insensitive match for one of the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

How does String substring work in Swift

Same frustration, this should not be that hard...

I compiled this example of getting positions for substring(s) from larger text:

//
// Play with finding substrings returning an array of the non-unique words and positions in text
//
//

import UIKit

let Bigstring = "Why is it so hard to find substrings in Swift3"
let searchStrs : Array<String>? = ["Why", "substrings", "Swift3"]

FindSubString(inputStr: Bigstring, subStrings: searchStrs)


func FindSubString(inputStr : String, subStrings: Array<String>?) ->    Array<(String, Int, Int)> {
    var resultArray : Array<(String, Int, Int)> = []
    for i: Int in 0...(subStrings?.count)!-1 {
        if inputStr.contains((subStrings?[i])!) {
            let range: Range<String.Index> = inputStr.range(of: subStrings![i])!
            let lPos = inputStr.distance(from: inputStr.startIndex, to: range.lowerBound)
            let uPos = inputStr.distance(from: inputStr.startIndex, to: range.upperBound)
            let element = ((subStrings?[i])! as String, lPos, uPos)
            resultArray.append(element)
        }
    }
    for words in resultArray {
        print(words)
    }
    return resultArray
}

returns ("Why", 0, 3) ("substrings", 26, 36) ("Swift3", 40, 46)

Rolling or sliding window iterator?

Just a quick contribution.

Since the current python docs don't have "window" in the itertool examples (i.e., at the bottom of http://docs.python.org/library/itertools.html), here's an snippet based on the code for grouper which is one of the examples given:

import itertools as it
def window(iterable, size):
    shiftedStarts = [it.islice(iterable, s, None) for s in xrange(size)]
    return it.izip(*shiftedStarts)

Basically, we create a series of sliced iterators, each with a starting point one spot further forward. Then, we zip these together. Note, this function returns a generator (it is not directly a generator itself).

Much like the appending-element and advancing-iterator versions above, the performance (i.e., which is best) varies with list size and window size. I like this one because it is a two-liner (it could be a one-liner, but I prefer naming concepts).

It turns out that the above code is wrong. It works if the parameter passed to iterable is a sequence but not if it is an iterator. If it is an iterator, the same iterator is shared (but not tee'd) among the islice calls and this breaks things badly.

Here is some fixed code:

import itertools as it
def window(iterable, size):
    itrs = it.tee(iterable, size)
    shiftedStarts = [it.islice(anItr, s, None) for s, anItr in enumerate(itrs)]
    return it.izip(*shiftedStarts)

Also, one more version for the books. Instead of copying an iterator and then advancing copies many times, this version makes pairwise copies of each iterator as we move the starting position forward. Thus, iterator t provides both the "complete" iterator with starting point at t and also the basis for creating iterator t + 1:

import itertools as it
def window4(iterable, size):
    complete_itr, incomplete_itr = it.tee(iterable, 2)
    iters = [complete_itr]
    for i in xrange(1, size):
        incomplete_itr.next()
        complete_itr, incomplete_itr = it.tee(incomplete_itr, 2)
        iters.append(complete_itr)
    return it.izip(*iters)

How to access site through IP address when website is on a shared host?

According with the HTTP/1.1 standard, the shared IP hosted site can be accessed by a GET request with the IP as URL and a header of the host.

Here there are two examples(wget and curl): $ wget --header 'Host:somerandomservice.com' http://67.225.235.59 $ curl --header 'Host:somerandomservice.com' http://67.225.235.59

Resources:

https://en.wikipedia.org/wiki/Shared_web_hosting_service

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23

How to replace NaNs by preceding values in pandas DataFrame?

You can use pandas.DataFrame.fillna with the method='ffill' option. 'ffill' stands for 'forward fill' and will propagate last valid observation forward. The alternative is 'bfill' which works the same way, but backwards.

import pandas as pd

df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
df = df.fillna(method='ffill')

print(df)
#   0  1  2
#0  1  2  3
#1  4  2  3
#2  4  2  9

There is also a direct synonym function for this, pandas.DataFrame.ffill, to make things simpler.

Getting the name of a variable as a string

Using the python-varname package, you can easily retrieve the name of the variables

https://github.com/pwwang/python-varname

As of v0.6.0, in your case, you can do:

from varname.helpers import Wrapper

foo = Wrapper(dict())

# foo.name == 'foo'
# foo.value == {}
foo.value['bar'] = 2

For list comprehension part, you can do:

n_jobs = Wrapper(<original_value>) 
users = Wrapper(<original_value>) 
queues = Wrapper(<original_value>) 
priorities = Wrapper(<original_value>) 

list_of_dicts = [n_jobs, users, queues, priorities]
columns = [d.name for d in list_of_dicts]
# ['n_jobs', 'users', 'queues', 'priorities']
# REMEMBER that you have to access the <original_value> by d.value

You can also try to retrieve the variable name DIRECTLY:

from varname import nameof

foo = dict()

fooname = nameof(foo)
# fooname == 'foo'

Note that this is working in this case as you expected:

n_jobs = <original_value>
d = n_jobs

nameof(d) # will return d, instead of n_jobs
# nameof only works directly with the variable

I am the author of this package. Please let me know if you have any questions or you can submit issues on Github.

How can I simulate mobile devices and debug in Firefox Browser?

Most web applications detects mobile devices based on the HTTP Headers.

If your web site also uses HTTP Headers to identify mobile device, you can do the following:

  1. Add Modify Headers plug in to your Firefox browser ( https://addons.mozilla.org/en-US/firefox/addon/modify-headers/ )
  2. Using plugin modify headers:
    • select Headers tab-> select Action 'ADD'
    • to simulate e.g. iPhone add a header with name User-Agent and value: Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3
    • click 'Add' button
  3. After that you should be able to see mobile version of you web application in Firefox and use Firebug plugin.

Hope it helps!

PHP UML Generator

You can use Visual Paradigm for UML. This might not be the best paid (it's US$699) product, just as an option if anyone would like to try. It can create class diagram from PHP and vice versa, and not only PHP, there's a bunch of language you can choose such as C#, C++, Ruby, Java, VB.NET, Python, Objective C, Perl, etc. There's also a trial you can check on.

Running npm command within Visual Studio Code

You have to do the following 3 steps to fix your issues:

1.Download Node.js from here.

  1. Install it and then add the path C:\Program Files\nodejs to your System variables.

  2. Then restart your visual studio code editor.

Happy code

How to push a docker image to a private repository

Simple working solution:

Go here https://hub.docker.com/ to create a PRIVATE repository with name for example johnsmith/private-repository this is the NAME/REPOSITORY you will use for your image when building the image.

  • First, docker login

  • Second, I use "docker build -t johnsmith/private-repository:01 ." (where 01 is my version name) to create image, and I use "docker images" to confirm the image created such as in this yellow box below: (sorry I can not paste the table format but the text string only)

johnsmith/private-repository(REPOSITORY) 01(TAG) c5f4a2861d6e(IMAGE ID) 2 days ago(CREATED) 305MB(SIZE)

Done!

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

I just ran into this and I was running under Release build configuration instead of Debug build configuration. Once I switched back to Debug my variable showed in the watch again.

How to position a Bootstrap popover?

Popover's Viewport (Bootstrap v3)

The best solution that will work for you in all occassions, especially if your website has a fluid width, is to use the viewport option of the Bootstrap Popover.

This will make the popover take width inside a selector you have assigned. So if the trigger button is on the right of that container, the bootstrap arrow will also appear on the right while the popover is inside that area. See jsfiddle.net

You can also use padding if you want some space from the edge of container. If you want no padding just use viewport: '.container'

$('#popoverButton').popover({
   container: 'body',
   placement: "bottom",
   html: true,   
   viewport: { selector: '.container', padding: 5 },
   content: '<strong>Hello Wooooooooooooooooooooooorld</strong>'
 });

in the following html example:

<div class="container">
   <button type="button" id="popoverButton">Click Me!</button>
</div>

and with CSS:

.container {
  text-align:right;
  width: 100px;
  padding: 20px;
  background: blue;
}

Popover's Boundary (Bootstrap v4)

Similar to viewport, in Bootstrap version 4, popover introduced the new option boundary

https://getbootstrap.com/docs/4.1/components/popovers/#options

How do I do multiple CASE WHEN conditions using SQL Server 2008?

Combining all conditions

select  a.* from tbl_Company a

where  a.Company_ID NOT IN (1,2)  

AND (   
        (0 = 
            CASE WHEN (@Fromdate = '' or @Todate='')
                THEN 0 
                ELSE 1  
            END
        )      -- if 0=0 true , if 0=1 fails (filter only when the fromdate and todate is present)
                OR
        (a.Created_Date between @Fromdate and @Todate )                 
    )

Listen for key press in .NET console app

From the video curse Building .NET Console Applications in C# by Jason Roberts at http://www.pluralsight.com

We could do following to have multiple running process

  static void Main(string[] args)
    {
        Console.CancelKeyPress += (sender, e) =>
        {

            Console.WriteLine("Exiting...");
            Environment.Exit(0);
        };

        Console.WriteLine("Press ESC to Exit");

        var taskKeys = new Task(ReadKeys);
        var taskProcessFiles = new Task(ProcessFiles);

        taskKeys.Start();
        taskProcessFiles.Start();

        var tasks = new[] { taskKeys };
        Task.WaitAll(tasks);
    }

    private static void ProcessFiles()
    {
        var files = Enumerable.Range(1, 100).Select(n => "File" + n + ".txt");

        var taskBusy = new Task(BusyIndicator);
        taskBusy.Start();

        foreach (var file in files)
        {
            Thread.Sleep(1000);
            Console.WriteLine("Procesing file {0}", file);
        }
    }

    private static void BusyIndicator()
    {
        var busy = new ConsoleBusyIndicator();
        busy.UpdateProgress();
    }

    private static void ReadKeys()
    {
        ConsoleKeyInfo key = new ConsoleKeyInfo();

        while (!Console.KeyAvailable && key.Key != ConsoleKey.Escape)
        {

            key = Console.ReadKey(true);

            switch (key.Key)
            {
                case ConsoleKey.UpArrow:
                    Console.WriteLine("UpArrow was pressed");
                    break;
                case ConsoleKey.DownArrow:
                    Console.WriteLine("DownArrow was pressed");
                    break;

                case ConsoleKey.RightArrow:
                    Console.WriteLine("RightArrow was pressed");
                    break;

                case ConsoleKey.LeftArrow:
                    Console.WriteLine("LeftArrow was pressed");
                    break;

                case ConsoleKey.Escape:
                    break;

                default:
                    if (Console.CapsLock && Console.NumberLock)
                    {
                        Console.WriteLine(key.KeyChar);
                    }
                    break;
            }
        }
    }
}

internal class ConsoleBusyIndicator
{
    int _currentBusySymbol;

    public char[] BusySymbols { get; set; }

    public ConsoleBusyIndicator()
    {
        BusySymbols = new[] { '|', '/', '-', '\\' };
    }
    public void UpdateProgress()
    {
        while (true)
        {
            Thread.Sleep(100);
            var originalX = Console.CursorLeft;
            var originalY = Console.CursorTop;

            Console.Write(BusySymbols[_currentBusySymbol]);

            _currentBusySymbol++;

            if (_currentBusySymbol == BusySymbols.Length)
            {
                _currentBusySymbol = 0;
            }

            Console.SetCursorPosition(originalX, originalY);
        }
    }

Get Mouse Position

import java.awt.MouseInfo;
import java.util.concurrent.TimeUnit;

public class Cords {

    public static void main(String[] args) throws InterruptedException {

        //get cords of mouse code, outputs to console every 1/2 second
        //make sure to import and include the "throws in the main method"

        while(true == true)
        {
        TimeUnit.SECONDS.sleep(1/2);
        double mouseX = MouseInfo.getPointerInfo().getLocation().getX();
        double mouseY = MouseInfo.getPointerInfo().getLocation().getY();
        System.out.println("X:" + mouseX);
        System.out.println("Y:" + mouseY);
        //make sure to import 
        }

    }

}

node.js + mysql connection pooling

It's a good approach.

If you just want to get a connection add the following code to your module where the pool is in:

var getConnection = function(callback) {
    pool.getConnection(function(err, connection) {
        callback(err, connection);
    });
};

module.exports = getConnection;

You still have to write getConnection every time. But you could save the connection in the module the first time you get it.

Don't forget to end the connection when you are done using it:

connection.release();

Dynamically converting java object of Object class to a given class when class name is known

If you didnt know that mojb is of type MyClass, then how can you create that variable?

If MyClass is an interface type, or a super type, then there is no need to do a cast.

Responsive Bootstrap Jumbotron Background Image

TLDR: Use background-size: 100% 100%;.

background-size: cover; may cut off some parts of the image producing poor results.

Using background-size: 100% 100%; you force the image to take up 100% of the parent element for both height and width.

See W3Schools for more information on this.

Here is a working, responsive jumbotron background image:

<div class="jumbotron"  style="background-image: url(http://yourImageUrl.jpg); background-size: 100% 100%;">
    <h1>Welcome</h1>
    <p class="lead">Your message here</p>
    <p><a href="http://www.YourLinkHere.com" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this

CAUSE: "Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app." In this case, "ACCESS_FINE_LOCATION" is a "dangerous permission and for that reason, you get this 'java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.' error (https://developer.android.com/training/permissions/requesting.html).

SOLUTION: Implementing the code provided at https://developer.android.com/training/permissions/requesting.html under the "Request the permissions you need" and "Handle the permissions request response" headings.

How to read file with async/await properly?

You can easily wrap the readFile command with a promise like so:

async function readFile(path) {
    return new Promise((resolve, reject) => {
      fs.readFile(path, 'utf8', function (err, data) {
        if (err) {
          reject(err);
        }
        resolve(data);
      });
    });
  }

then use:

await readFile("path/to/file");

Difference between document.addEventListener and window.addEventListener?

You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window and document both fit the bill (with just a few differences).

From mozilla dev network:

addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.

So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.

Get Date in YYYYMMDD format in windows batch file

You can try this ! This should work on windows machines.

for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"

Combine multiple Collections into a single logical Collection?

Plain Java 8 solutions using a Stream.

Constant number

Assuming private Collection<T> c, c2, c3.

One solution:

public Stream<T> stream() {
    return Stream.concat(Stream.concat(c.stream(), c2.stream()), c3.stream());
}

Another solution:

public Stream<T> stream() {
    return Stream.of(c, c2, c3).flatMap(Collection::stream);
}

Variable number

Assuming private Collection<Collection<T>> cs:

public Stream<T> stream() {
    return cs.stream().flatMap(Collection::stream);
}

Extract substring in Bash

just try to use cut -c startIndx-stopIndx

Location of hibernate.cfg.xml in project?

My problem was that i had a exculding patern in the resorces folder. After removing it the

config.configure(); 

worked for me. With the structure src/java/...HibernateUtil.java and cfg file under src/resources.

Rolling back local and remote git repository by 1 commit

If nobody has pulled your remote repo yet, you can change your branch HEAD and force push it to said remote repo:

git reset --hard HEAD^ 
git push -f 

(or, if you have direct access to the remote repo, you can change its HEAD reference even though it is a bare repo)

Note, as commented by alien-technology in the comments below, on Windows (CMD session), you would need ^^:

git reset --hard HEAD^^
git push -f 

Update since 2011:
Using git push --force-with-lease (that I present here, introduced in 2013 with Git 1.8.5) is safer.

See Schwern's answer for illustration.


What if somebody has already pulled the repo? What would I do then?

Then I would suggest something that doesn't rewrite the history:

  • git revert locally your last commit (creating a new commit that reverses what the previous commit did)
  • push the 'revert' generated by git revert.

python and sys.argv

BTW you can pass the error message directly to sys.exit:

if len(sys.argv) < 2:
    sys.exit('Usage: %s database-name' % sys.argv[0])

if not os.path.exists(sys.argv[1]):
    sys.exit('ERROR: Database %s was not found!' % sys.argv[1])

Select and trigger click event of a radio button in jquery

In my case i had to load images on radio button click, I just uses the regular onclick event and it worked for me.

 <input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion"  onclick="return get_images(this, {{color.id}})">

<script>
  function get_images(obj, color){
    console.log($("input[type='radio'][name='colors']:checked").val());

  }
  </script>

Pandas Merging 101

This post will go through the following topics:

  • Merging with index under different conditions
    • options for index-based joins: merge, join, concat
    • merging on indexes
    • merging on index of one, column of other
  • effectively using named indexes to simplify merging syntax

BACK TO TOP



Index-based joins

TL;DR

There are a few options, some simpler than others depending on the use case.

  1. DataFrame.merge with left_index and right_index (or left_on and right_on using names indexes)
    • supports inner/left/right/full
    • can only join two at a time
    • supports column-column, index-column, index-index joins
  2. DataFrame.join (join on index)
    • supports inner/left (default)/right/full
    • can join multiple DataFrames at a time
    • supports index-index joins
  3. pd.concat (joins on index)
    • supports inner/full (default)
    • can join multiple DataFrames at a time
    • supports index-index joins

Index to index joins

Setup & Basics

import pandas as pd
import numpy as np

np.random.seed([3, 14])
left = pd.DataFrame(data={'value': np.random.randn(4)}, 
                    index=['A', 'B', 'C', 'D'])    
right = pd.DataFrame(data={'value': np.random.randn(4)},  
                     index=['B', 'D', 'E', 'F'])
left.index.name = right.index.name = 'idxkey'

left
           value
idxkey          
A      -0.602923
B      -0.402655
C       0.302329
D      -0.524349

right
 
           value
idxkey          
B       0.543843
D       0.013135
E      -0.326498
F       1.385076

Typically, an inner join on index would look like this:

left.merge(right, left_index=True, right_index=True)

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

Other joins follow similar syntax.

Notable Alternatives

  1. DataFrame.join defaults to joins on the index. DataFrame.join does a LEFT OUTER JOIN by default, so how='inner' is necessary here.

     left.join(right, how='inner', lsuffix='_x', rsuffix='_y')
    
              value_x   value_y
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    Note that I needed to specify the lsuffix and rsuffix arguments since join would otherwise error out:

     left.join(right)
     ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
    

    Since the column names are the same. This would not be a problem if they were differently named.

     left.rename(columns={'value':'leftvalue'}).join(right, how='inner')
    
             leftvalue     value
     idxkey                     
     B       -0.402655  0.543843
     D       -0.524349  0.013135
    
  2. pd.concat joins on the index and can join two or more DataFrames at once. It does a full outer join by default, so how='inner' is required here..

     pd.concat([left, right], axis=1, sort=False, join='inner')
    
                value     value
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    For more information on concat, see this post.


Index to Column joins

To perform an inner join using index of left, column of right, you will use DataFrame.merge a combination of left_index=True and right_on=....

right2 = right.reset_index().rename({'idxkey' : 'colkey'}, axis=1)
right2
 
  colkey     value
0      B  0.543843
1      D  0.013135
2      E -0.326498
3      F  1.385076

left.merge(right2, left_index=True, right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135

Other joins follow a similar structure. Note that only merge can perform index to column joins. You can join on multiple columns, provided the number of index levels on the left equals the number of columns on the right.

join and concat are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index.


Effectively using Named Index [pandas >= 0.23]

If your index is named, then from pandas >= 0.23, DataFrame.merge allows you to specify the index name to on (or left_on and right_on as necessary).

left.merge(right, on='idxkey')

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

For the previous example of merging with the index of left, column of right, you can use left_on with the index name of left:

left.merge(right2, left_on='idxkey', right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135


Continue Reading

Jump to other topics in Pandas Merging 101 to continue learning:

* you are here

Update statement using with clause

The WITH syntax appears to be valid in an inline view, e.g.

UPDATE (WITH comp AS ...
        SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
   SET SomeColumn=ComputedValue;

But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.

You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:

MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON (t.id = comp.id)
WHEN MATCHED THEN UPDATE SET SomeColumn=ComputedValue;

But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING clause arbitrarily complex, incorporating multiple WITH clauses.

How to edit/save a file through Ubuntu Terminal

If you are not root user then, use following commands:

There are two ways to do it -

1.

sudo vi path_to_file/file_name

Press Esc and then type below respectively

:wq //save and exit
:q! //exit without saving
  1. sudo nano path_to_file/file_name

When using nano: after you finish editing press ctrl+x then it will ask save Y/N.
If you want to save press Y, if not press N. And press enter to exit the editor.

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

I sovled this errors by modifying the Database charset.Old Database charset is cp1252 and i conver to utf-8

How to print multiple variable lines in Java

You can do it with 1 printf:

System.out.printf("First Name: %s\nLast Name: %s",firstname, lastname);

How do you find out the type of an object (in Swift)?

Here is 2 ways I recommend doing it:

if let thisShape = aShape as? Square 

Or:

aShape.isKindOfClass(Square)

Here is a detailed example:

class Shape { }
class Square: Shape { } 
class Circle: Shape { }

var aShape = Shape()
aShape = Square()

if let thisShape = aShape as? Square {
    println("Its a square")
} else {
    println("Its not a square")
}

if aShape.isKindOfClass(Square) {
    println("Its a square")
} else {
    println("Its not a square")
}

SQL Query to search schema of all tables

My favorite...

SELECT objParent.name AS parent, obj.name, col.*
FROM sysobjects obj 
    LEFT JOIN syscolumns col
        ON obj.id = col.id
    LEFT JOIN sysobjects objParent
        ON objParent.id = obj.parent_obj
WHERE col.name LIKE '%Comment%'
   OR obj.name LIKE '%Comment%'

Above I'm searching for "Comment".

Drop the percent signs if you want a direct match.

This searches tables, fields and things like primary key names, constraints, views, etc.

And when you want to search in StoredProcs after monkeying with the tables (and need to make the procs match), use the following...

SELECT name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Comment%'

Hope that helps, I find these two queries to be extremely useful.

Call function with setInterval in jQuery?

jQuery is just a set of helpers/libraries written in Javascript. You can still use all Javascript features, so you can call whatever functions, also from inside jQuery callbacks. So both possibilities should be okay.

How do I change the android actionbar title and icon

The action bar title will, by default, use the label of the current activity, but you can also set it programmatically via ActionBar.setTitle().

To implement the "Back" (more precisely, "Up") button functionality you're talking about, read the "Using the App Icon for Navigation" section of the Action Bar developer guide.

Finally, to change the icon, the guide covers that as well. In short, the action bar will display the image supplied in android:icon in your manifest's application or activity element, if there is one. The typical practice is to create an application icon (in all of the various densities you'll need) named ic_launcher.png, and place it in your drawable-* directories.

How to receive serial data using android bluetooth

Take a look at incredible Bluetooth Serial class that has onResume() ability that helped me so much. I hope this helps ;)

Extending from two classes

The creators of java decided that the problems of multiple inheritance outweigh the benefits, so they did not include multiple inheritance. You can read about one of the largest issues of multiple inheritance (the double diamond problem) here.

The two most similar concepts are interface implementation and including objects of other classes as members of the current class. Using default methods in interfaces is almost exactly the same as multiple inheritance, however it is considered bad practice to use an interface with only default methods.

JavaScript moving element in the DOM

Trivial with jQuery

$('#div1').insertAfter('#div3');
$('#div3').insertBefore('#div2');

If you want to do it repeatedly, you'll need to use different selectors since the divs will retain their ids as they are moved around.

$(function() {
    setInterval( function() {
        $('div:first').insertAfter($('div').eq(2));
        $('div').eq(1).insertBefore('div:first');
    }, 3000 );
});

What svn command would list all the files modified on a branch?

This will do it I think:

svn diff -r 22334:HEAD --summarize <url of the branch>

What is the Java equivalent for LINQ?

For basic functional collections, Java 8 has it built in, most of the major non-Java JVM languages have it built in (Scala, Clojure, etc), and you can get add on libs for earlier Java versions.

For full language integrated access to a SQL database, Scala (runs on the JVM) has Slick

Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

An asynchronously loaded script is likely going to run AFTER the document has been fully parsed and closed. Thus, you can't use document.write() from such a script (well technically you can, but it won't do what you want).

You will need to replace any document.write() statements in that script with explicit DOM manipulations by creating the DOM elements and then inserting them into a particular parent with .appendChild() or .insertBefore() or setting .innerHTML or some mechanism for direct DOM manipulation like that.

For example, instead of this type of code in an inline script:

<div id="container">
<script>
document.write('<span style="color:red;">Hello</span>');
</script>
</div>

You would use this to replace the inline script above in a dynamically loaded script:

var container = document.getElementById("container");
var content = document.createElement("span");
content.style.color = "red";
content.innerHTML = "Hello";
container.appendChild(content);

Or, if there was no other content in the container that you needed to just append to, you could simply do this:

var container = document.getElementById("container");
container.innerHTML = '<span style="color:red;">Hello</span>';

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Start by figuring out what your current working directory is for your running script.
Add this line at the beginning:

puts Dir.pwd.

This will tell you in which current working directory ruby is running your script. You will most likely see it's not where you assume it is. Then make sure you're specifying pathnames properly for windows. See the docs here how to properly format pathnames for windows:

http://www.ruby-doc.org/core/classes/IO.html

Then either use Dir.chdir to change the working directory to the place where text.txt is, or specify the absolute pathname to the file according to the instructions in the IO docs above. That SHOULD do it...

EDIT

Adding a 3rd solution which might be the most convenient one, if you're putting the text files among your script files:

Dir.chdir(File.dirname(__FILE__))

This will automatically change the current working directory to the same directory as the .rb file that is running the script.

How do I give PHP write access to a directory?

Set the owner of the directory to the user running apache. Often nobody on linux

chown nobody:nobody <dirname>

This way your folder will not be world writable, but still writable for apache :)

How to convert a string to a date in sybase

Several ways to accomplish that but be aware that your DB date_format option & date_order option settings could affect the incoming format:

Select 
   cast('2008-09-16' as date)
   convert(date,'16/09/2008',103)
   date('2008-09-16')
from dummy;

Using floats with sprintf() in embedded C

Yes you can. However, it depends on the C-library that you are linking against and you need to be aware of the consequences.

Since you are programming for embedded applications, realise that floating-point support is emulated for a lot of embedded architectures. Compiling in this floating-point support will end up increasing the size of your executable significantly.

javascript create empty array of a given size

1) To create new array which, you cannot iterate over, you can use array constructor:

Array(100) or new Array(100)


2) You can create new array, which can be iterated over like below:

a) All JavaScript versions

  • Array.apply: Array.apply(null, Array(100))

b) From ES6 JavaScript version

  • Destructuring operator: [...Array(100)]
  • Array.prototype.fill Array(100).fill(undefined)
  • Array.from Array.from({ length: 100 })

You can map over these arrays like below.

  • Array(4).fill(null).map((u, i) => i) [0, 1, 2, 3]

  • [...Array(4)].map((u, i) => i) [0, 1, 2, 3]

  • Array.apply(null, Array(4)).map((u, i) => i) [0, 1, 2, 3]

  • Array.from({ length: 4 }).map((u, i) => i) [0, 1, 2, 3]

How to get history on react-router v4?

If you are using redux and redux-thunk the best solution will be using react-router-redux

// then, in redux actions for example
import { push } from 'react-router-redux'

dispatch(push('/some/path'))

It's important to see the docs to do some configurations.

Django Cookies, how can I set them?

Anyone interested in doing this should read the documentation of the Django Sessions framework. It stores a session ID in the user's cookies, but maps all the cookies-like data to your database. This is an improvement on the typical cookies-based workflow for HTTP requests.

Here is an example with a Django view ...

def homepage(request):

    request.session.setdefault('how_many_visits', 0)
    request.session['how_many_visits'] += 1

    print(request.session['how_many_visits'])

    return render(request, 'home.html', {})

If you keep visiting the page over and over, you'll see the value start incrementing up from 1 until you clear your cookies, visit on a new browser, go incognito, or do anything else that sidesteps Django's Session ID cookie.

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

? is called Ternary (conditional) operator : example

How to compile python script to binary executable

Or use PyInstaller as an alternative to py2exe. Here is a good starting point. PyInstaller also lets you create executables for linux and mac...

Here is how one could fairly easily use PyInstaller to solve the issue at hand:

pyinstaller oldlogs.py

From the tool's documentation:

PyInstaller analyzes myscript.py and:

  • Writes myscript.spec in the same folder as the script.
  • Creates a folder build in the same folder as the script if it does not exist.
  • Writes some log files and working files in the build folder.
  • Creates a folder dist in the same folder as the script if it does not exist.
  • Writes the myscript executable folder in the dist folder.

In the dist folder you find the bundled app you distribute to your users.

SSL "Peer Not Authenticated" error with HttpClient 4.1

keytool -import -v -alias cacerts -keystore cacerts.jks -storepass changeit -file C:\cacerts.cer

Using "If cell contains #N/A" as a formula condition.

A possible alternative approach in Excel 2010 or later versions:

AGGREGATE(6,6,A1,B1)

In AGGREGATE function the first 6 indicates PRODUCT operation and the second 6 denotes "ignore errors"

[untested]

jQuery getTime function

@nickf's correct. However, to be a little more precise:

// if you try to print it, it will return something like:
// Sat Mar 21 2009 20:13:07 GMT-0400 (Eastern Daylight Time)
// This time comes from the user's machine.
var myDate = new Date();

So if you want to display it as mm/dd/yyyy, you would do this:

var displayDate = (myDate.getMonth()+1) + '/' + (myDate.getDate()) + '/' + myDate.getFullYear();

Check out the full reference of the Date object. Unfortunately it is not nearly as nice to print out various formats as it is with other server-side languages. For this reason there-are-many-functions available in the wild.

Display tooltip on Label's hover?

If you also have jQuery UI, you can add this:

$(document).ready(function () {
  $(document).tooltip();
});

You then need a title instead of a hidden input. RGraham already posted an answer doing this for you :P

What does it mean by command cd /d %~dp0 in Windows

~dp0 : d=drive, p=path, %0=full path\name of this batch-file.

cd /d %~dp0 will change the path to the same, where the batch file resides.

See for /? or call / for more details about the %~... modifiers.
See cd /? about the /d switch.

Want to upgrade project from Angular v5 to Angular v6

Check the step by step upgrade details from Angular 5 to Angular 6. These provides details on issues you encounter during upgrade and how to resolve them.

  • Update your node version to 8 or above and Install Angular cli latest globally by npm i -g @angular/cli@latest.
  • Angular 6 uses angular.json as configuration file instead of .anguar-cli.json. Also tslint has been changed. Check https://github.com/angular/angular-cli/wiki/angular-workspace for latest configuration details. You have to move any of your existing configuration to new configuration file.
  • To do this create another dummy project with latest cli using ng new ‘your-project’ and same defaults such as prefix, style etc you used earlier for your project. Create new project with cli https://github.com/angular/angular-cli/wiki/new
  • Use https://update.angular.io/ to check what has been changed from your current version of Angular ? Angular 6. It provides usage of how to change/fix them.
  • Follow the steps above and copy/update the angular.json file created in step2. Do npm i in your project to get all dependencies and do npm update
  • Now comes the big part. RxJS upgrade and resolving conflicts. RxJS has standardised imports of operators and Observable creators with this release. Do npm i -g rxjs-tslint and add below lint configuration in tslint.json
{
  "rulesDirectory": [
    "node_modules/rxjs-tslint"
  ],
  "rules": {
    "rxjs-collapse-imports": true,
    "rxjs-pipeable-operators-only": true,
    "rxjs-no-static-observable-methods": true,
    "rxjs-proper-imports": true
  }
}
  • Now run ng lint --fix. This fixes few items but most of the remaining issues will be highlighted and you have to fix it manually.

Operators Name change:

do -> tap, 
catch -> catchError, 
switch -> switchAll, 
finally -> finalize

All operators moved to rxjs/operators

import { map, filter, reduce } from 'rxjs/operators';

Observable creation methods are moved to rxjs

   import { Observable, Subject, of, from } from 'rxjs'; 

You are all set. Welcome to Angular 6 :) Check my blog post here on how to upgrade

Resize image in the wiki of GitHub using Markdown

I have used methods described above. Now I am using the method which is a way similiar but more simple to me.

  1. First create add README.md file to your project.
  2. Then upload screenshoots or whatever description images needed to your project main directory.
  3. After uploading image Assets use html to refer these assets directly without using link like below

Like this:

<img src="icon.jpg" width="324" height="324">

<p align="center">
  <img src="screen1.png" width="256" height="455">
  <img src="screen2.png" width="256" height="455">
  <img src="screen3.png" width="256" height="455">
</p>

On above example I have used paragraph to align images side by side. If you are going to use single image just use the code as below

<img src="icon.jpg" width="324" height="324">

Have a nice day!

Dynamically change color to lighter or darker by percentage CSS (Javascript)

This is an old question, but most of the answers require the use of a preprocessor or JavaScript to operate, or they not only affect the color of the element but also the color of the elements contained within it. I am going to add a kind-of-complicated CSS-only way of doing the same thing. Probably in the future, with the more advanced CSS functions, it will be easier to do.

The idea is based on using:

  • RGB colors, so you have separate values for red, green, and blue;
  • CSS variables, to store the color values and the darkness; and
  • The calc function, to apply the change.

By default darkness will be 1 (for 100%, the regular color), and if you multiply by a number between 0 and 1, you'll be making the color darker. For example, if you multiply by 0.85 each of the values, you'll be making the colors 15% darker (100% - 15% = 85% = 0.85).

Here is an example, I created three classes: .dark, .darker, and .darkest that will make the original color 25%, 50%, and 75% darker respectively:

_x000D_
_x000D_
html {_x000D_
  --clarity: 1;_x000D_
}_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
  line-height: 100px;_x000D_
  color: white;_x000D_
  text-align: center;_x000D_
  font-family: arial, sans-serif;_x000D_
  font-size: 20px;_x000D_
  background: rgba(_x000D_
                  calc(var(--r) * var(--clarity)), _x000D_
                  calc(var(--g) * var(--clarity)), _x000D_
                  calc(var(--b) * var(--clarity))_x000D_
                );_x000D_
}_x000D_
_x000D_
.dark    { --clarity: 0.75; }_x000D_
.darker  { --clarity: 0.50; }_x000D_
.darkest { --clarity: 0.25; }_x000D_
_x000D_
.red {_x000D_
  --r: 255;_x000D_
  --g: 0;_x000D_
  --b: 0;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
  --r: 205;_x000D_
  --g: 30;_x000D_
  --b: 205;_x000D_
}
_x000D_
<div class="red">0%</div>_x000D_
<div class="red dark">25%</div>_x000D_
<div class="red darker">50%</div>_x000D_
<div class="red darkest">75%</div>_x000D_
_x000D_
<br/><br/>_x000D_
_x000D_
<div class="purple">0%</div>_x000D_
<div class="purple dark">25%</div>_x000D_
<div class="purple darker">50%</div>_x000D_
<div class="purple darkest">75%</div>
_x000D_
_x000D_
_x000D_

How do I create a new Git branch from an old commit?

git checkout -b NEW_BRANCH_NAME COMMIT_ID

This will create a new branch called 'NEW_BRANCH_NAME' and check it out.

("check out" means "to switch to the branch")

git branch NEW_BRANCH_NAME COMMIT_ID

This just creates the new branch without checking it out.


in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:

git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME

Interface defining a constructor signature?

You can't.

Interfaces define contracts that other objects implement and therefore have no state that needs to be initialized.

If you have some state that needs to be initialized, you should consider using an abstract base class instead.

Gerrit error when Change-Id in commit messages are missing

It is because Gerrit is configured to require Change-Id in the commit messages.

http://gerrit.googlecode.com/svn-history/r6114/documentation/2.1.7/error-missing-changeid.html

You have to change the messages of every commit that you are pushing to include the change id ( using git filter-branch ) and only then push.

How to open a WPF Popup when another control is clicked, using XAML markup only?

I did something simple, but it works.

I used a typical ToggleButton, which I restyled as a textblock by changing its control template. Then I just bound the IsChecked property on the ToggleButton to the IsOpen property on the popup. Popup has some properties like StaysOpen that let you modify the closing behavior.

The following works in XamlPad.

 <StackPanel>
  <ToggleButton Name="button"> 
    <ToggleButton.Template>
      <ControlTemplate TargetType="ToggleButton">
        <TextBlock>Click Me Here!!</TextBlock>
      </ControlTemplate>      
    </ToggleButton.Template>
  </ToggleButton>
  <Popup IsOpen="{Binding IsChecked, ElementName=button}" StaysOpen="False">
    <Border Background="LightYellow">
      <TextBlock>I'm the popup</TextBlock>
    </Border>
  </Popup> 
 </StackPanel>

Split code over multiple lines in an R script

Bah, comments are too small. Anyway, @Dirk is very right.

R doesn't need to be told the code starts at the next line. It is smarter than Python ;-) and will just continue to read the next line whenever it considers the statement as "not finished". Actually, in your case it also went to the next line, but R takes the return as a character when it is placed between "".

Mind you, you'll have to make sure your code isn't finished. Compare

a <- 1 + 2
+ 3

with

a <- 1 + 2 +
3

So, when spreading code over multiple lines, you have to make sure that R knows something is coming, either by :

  • leaving a bracket open, or
  • ending the line with an operator

When we're talking strings, this still works but you need to be a bit careful. You can open the quotation marks and R will read on until you close it. But every character, including the newline, will be seen as part of the string :

x <- "This is a very
long string over two lines."
x
## [1] "This is a very\nlong string over two lines."
cat(x)
## This is a very
## long string over two lines.

That's the reason why in this case, your code didn't work: a path can't contain a newline character (\n). So that's also why you better use the solution with paste() or paste0() Dirk proposed.

JavaScript: SyntaxError: missing ) after argument list

You got an extra } to many as seen below:

var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
    nav[i].addEventListener('click',function(){
            console.log('haha');
        } // <-- REMOVE THIS :)
    }, false);
};

A very good tool for those things is jsFiddle. I have created a fiddle with your invalid code and when clicking the TidyUp button it formats your code which makes it clearer if there are any possible mistakes with missing braces.


DEMO - Your code in a fiddle, have a play :)


How to set IntelliJ IDEA Project SDK

For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure enter image description here Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 enter image description here Now Just go Project under Project settings and select the project SDK. enter image description here

How do you perform address validation?

Here's a free and sort of "outside the box" way to do it. Not 100% perfect, but it should reject blatantly non-existent addresses.

Submit the entire address to Google's geocoding web service. This service attempts to return the exact coordinates of the location you feed it, i.e. latitude and longitude.

In my experience if the address is invalid you will get a result of 602 from the service. There's definitely a possibility of false positives or false negatives, but used in conjunction with other consistency checks it could be useful.

(Yahoo's geocoding web service, on the other hand, will return the coordinates of the center of the town if the town exists but the rest of the address is bogus. Potentially useful as long as you pay close attention to the "precision" field in the result).

jquery $('.class').each() how many items?

Use the .length property. It is not a function.

alert($('.class').length); // alerts a nonnegative number 

Turn off textarea resizing

//CSS:
.textarea {
    resize: none;
    min-width: //-> Integer number of pixels
    min-height: //-> Integer number of pixels
    max-width: //-> min-width
    max-height: //-> min-height
}

above code works on most browsers

//HTML:
<textarea id='textarea' draggable='false'></textarea>

do both for it to work on the maximum number of browsers

pandas: merge (join) two data frames on multiple columns

Try this

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

left_on : label or list, or array-like Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns

right_on : label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs

CSS3 Transform Skew One Side

I know this is old, but I would like to suggest using a linear-gradient to achieve the same effect instead of margin offset. This is will maintain any content at its original place.

http://jsfiddle.net/zwXaf/2/

HTML

<ul>
    <li><a href="#">One</a></li>
    <li><a href="#">Two</a></li>
    <li><a href="#">Three</a></li>
</ul>

CSS

/* reset */
ul, li, a {
    margin: 0; padding: 0;
}
/* nav stuff */
ul, li, a {
    display: inline-block;
    text-align: center;
}
/* appearance styling */
ul {
    /* hacks to make one side slant only */
    overflow: hidden;
    background: linear-gradient(to right, red, white, white, red);
}
li {
    background-color: red;
     transform:skewX(-20deg);
    -ms-transform:skewX(-20deg);
    -webkit-transform:skewX(-20deg);
}
li a {
    padding: 3px 6px 3px 6px;
    color: #ffffff;
    text-decoration: none;
    width: 80px;
     transform:skewX(20deg);
    -ms-transform:skewX(20deg);
    -webkit-transform:skewX(20deg);
}

Keytool is not recognized as an internal or external command

Make sure JAVA_HOME is set and the path in environment variables. The PATH should be able to find the keytools.exe

Open “Windows search” and search for "Environment Variables"

Under “System variables” click the “New…” button and enter JAVA_HOME as “Variable name” and the path to your Java JDK directory under “Variable value” it should be similar to this C:\Program Files\Java\jre1.8.0_231

how to get the first and last days of a given month

$month = 10; // october

$firstday = date('01-' . $month . '-Y');
$lastday = date(date('t', strtotime($firstday)) .'-' . $month . '-Y');

Automatically resize images with browser size using CSS

To make the images flexible, simply add max-width:100% and height:auto. Image max-width:100% and height:auto works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to add width:auto\9 for IE8.

source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

for example :

img {
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
}

and then any images you add simply using the img tag will be flexible

JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).

How to validate GUID is a GUID

Will return the Guid if it is valid Guid, else it will return Guid.Empty

if (!Guid.TryParse(yourGuidString, out yourGuid)){
          yourGuid= Guid.Empty;
}

How to find the array index with a value?

When the lists aren't extremely long, this is the best way I know:

function getIndex(val) {
    for (var i = 0; i < imageList.length; i++) {
        if (imageList[i] === val) {
            return i;
        }
    }
}

var imageList = [100, 200, 300, 400, 500];
var index = getIndex(200);

Run CRON job everyday at specific time

From cron manual http://man7.org/linux/man-pages/man5/crontab.5.html:

Lists are allowed. A list is a set of numbers (or ranges) separated by commas. Examples: "1,2,5,9", "0-4,8-12".

So in this case it would be:

30 10,14 * * *

Is there an equivalent of CSS max-width that works in HTML emails?

Yes, there is a way to emulate max-width using a table, thus giving you both responsive and Outlook-friendly layout. What's more, this solution doesn't require conditional comments.

Suppose you want the equivalent of a centered div with max-width of 350px. You create a table, set the width to 100%. The table has three cells in a row. Set the width of the center TD to 350 (using the HTML width attribute, not CSS), and there you go.

If you want your content aligned left instead of centered, just leave out the first empty cell.

Example:

<table border="0" cellspacing="0" width="100%">
    <tr>
        <td></td>
        <td width="350">The width of this cell should be a maximum of 
                  350 pixels, but shrink to widths less than 350 pixels.
        </td>
        <td></td>
     </tr>
</table> 

In the jsfiddle I give the table a border so you can see what's going on, but obviously you wouldn't want one in real life:

http://jsfiddle.net/YcwM7/

iPhone UITextField - Change placeholder text color

With this we can change the color of textfield's placeholder text in iOS

[self.userNameTxt setValue:[UIColor colorWithRed:41.0/255.0 green:91.0/255.0 blue:106.0/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];

How to properly exit a C# application?

In this case, the most proper way to exit the application in to override onExit() method in App.xaml.cs:

protected override void OnExit(ExitEventArgs e) {
    base.OnExit(e); 
}

Bootstrap table without stripe / borders

Bootstrap supports scss, and he has a special variables. If this is a case then you can add in your main variables.scss file

$table-border-width: 0;

More info here https://github.com/twbs/bootstrap/blob/6ffb0b48e455430f8a5359ed689ad64c1143fac2/scss/_variables.scss#L347-L380

Allow only numeric value in textbox using Javascript

Please note that, you should allow "system" key as well

    $(element).keydown(function (e) {
    var code = (e.keyCode ? e.keyCode : e.which), value;
    if (isSysKey(code) || code === 8 || code === 46) {
        return true;
    }

    if (e.shiftKey || e.altKey || e.ctrlKey) {
        return ;
    }

    if (code >= 48 && code <= 57) {
        return true;
    }

    if (code >= 96 && code <= 105) {
        return true;
    }

    return false;
});

function isSysKey(code) {
    if (code === 40 || code === 38 ||
            code === 13 || code === 39 || code === 27 ||
            code === 35 ||
            code === 36 || code === 37 || code === 38 ||
            code === 16 || code === 17 || code === 18 ||
            code === 20 || code === 37 || code === 9 ||
            (code >= 112 && code <= 123)) {
        return true;
    }

    return false;
}

Finding a branch point with Git?

Not quite a solution to the question but I thought it was worth noting the the approach I use when I have a long-living branch:

At the same time I create the branch, I also create a tag with the same name but with an -init suffix, for example feature-branch and feature-branch-init.

(It is kind of bizarre that this is such a hard question to answer!)

Compare two Byte Arrays? (Java)

Check out the static java.util.Arrays.equals() family of methods. There's one that does exactly what you want.

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

I got the same problems. I solved my problem by updating gradle.build for each sub-module to latest compiler version.

What is the common header format of Python files?

I strongly favour minimal file headers, by which I mean just:

  • The hashbang (#! line) if this is an executable script
  • Module docstring
  • Imports, grouped in the standard way, eg:
  import os    # standard library
  import sys

  import requests  # 3rd party packages

  from mypackage import (  # local source
      mymodule,
      myothermodule,
  )

ie. three groups of imports, with a single blank line between them. Within each group, imports are sorted. The final group, imports from local source, can either be absolute imports as shown, or explicit relative imports.

Everything else is a waste of time, visual space, and is actively misleading.

If you have legal disclaimers or licencing info, it goes into a separate file. It does not need to infect every source code file. Your copyright should be part of this. People should be able to find it in your LICENSE file, not random source code.

Metadata such as authorship and dates is already maintained by your source control. There is no need to add a less-detailed, erroneous, and out-of-date version of the same info in the file itself.

I don't believe there is any other data that everyone needs to put into all their source files. You may have some particular requirement to do so, but such things apply, by definition, only to you. They have no place in “general headers recommended for everyone”.

Twitter bootstrap scrollable modal

Your modal is being hidden in firefox, and that is because of the negative margin declaration you have inside your general stylesheet:

.modal {
    margin-top: -45%; /* remove this */
    max-height: 90%;
    overflow-y: auto;
}

Remove the negative margin and everything works just fine.

Splitting comma separated string in a PL/SQL stored proc

Many good solutions have been provided already. However, if he text is provided in a very simple comma delimited format or similar, and speed is of importance, then I have for you a solution with a TABLE function (in PL/SQL). I have also provided a rundown of some other solutions.

Please see more on the Blog Entry on Parsing a CSV into multiple columns.

Free Rest API to retrieve current datetime as string (timezone irrelevant)

TimezoneDb provides a free API: http://timezonedb.com/api

GenoNames also has a RESTful API available to get the current time for a given location: http://www.geonames.org/export/ws-overview.html.

You can use Greenwich, UK if you'd like GMT.

Is there a typescript List<> and/or Map<> class/library?

It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.

Map:

class Map<T> {
    private items: { [key: string]: T };

    constructor() {
        this.items = {};
    }

    add(key: string, value: T): void {
        this.items[key] = value;
    }

    has(key: string): boolean {
        return key in this.items;
    }

    get(key: string): T {
        return this.items[key];
    }
}

List:

class List<T> {
    private items: Array<T>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(value);
    }

    get(index: number): T {
        return this.items[index];
    }
}

I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...

As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:

class ListItem<T> {
    private list: List<T>;
    private index: number;

    public value: T;

    constructor(list: List<T>, value: T, index: number) {
        this.list = list;
        this.index = index;
        this.value = value;
    }

    prev(): ListItem<T> {
        return this.list.get(this.index - 1);
    }

    next(): ListItem<T> {
        return this.list.get(this.index + 1);   
    }
}

class List<T> {
    private items: Array<ListItem<T>>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(new ListItem<T>(this, value, this.size()));
    }

    get(index: number): ListItem<T> {
        return this.items[index];
    }
}

Here too you're looking at untested code..

Hope this helps.


Edit - as this answer still gets some attention

Javascript has a native Map object so there's no need to create your own:

let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1