Programs & Examples On #Image.createimage

Oracle PL/SQL - How to create a simple array variable?

You can use VARRAY for a fixed-size array:

   type array_t is varray(3) of varchar2(10);
   array array_t := array_t('Matt', 'Joanne', 'Robert');
   for i in 1..array.count loop
   end loop;

Or TABLE for an unbounded array:

   type array_t is table of varchar2(10);

The word "table" here has nothing to do with database tables, confusingly. Both methods create in-memory arrays.

With either of these you need to both initialise and extend the collection before adding elements:

   type array_t is varray(3) of varchar2(10);
   array array_t := array_t(); -- Initialise it
   for i in 1..3 loop
      array.extend(); -- Extend it
      array(i) := 'x';
   end loop;

The first index is 1 not 0.

MVC: How to Return a String as JSON

Yeah that's it without no further issues, to avoid raw string json this is it.

    public ActionResult GetJson()
        var json = System.IO.File.ReadAllText(

        return new ContentResult
            Content = json,
            ContentType = "application/json",
            ContentEncoding = Encoding.UTF8

NOTE: please note that method return type of JsonResult is not working for me, since JsonResult and ContentResult both inherit ActionResult but there is no relationship between them.

Can I use Homebrew on Ubuntu?

October 2019 - Ubuntu 18.04 on WSL with oh-my-zsh; the instructions here worked perfectly -

(first, install pre-requisites using sudo apt-get install build-essential curl file git)

finally create a ~/.zprofile with the following contents: emulate sh -c '. ~/.profile'

How do you exit from a void function in C++?

Use a return statement!



if (condition) return;

You don't need to (and can't) specify any values, if your method returns void.


Replace Into seems like an option. Or you can check with


This will insert or delete then insert. I tend to go for a IF NOT EXISTS check first.

Hide/encrypt password in bash file to stop accidentally seeing it

There's a more convenient way to store passwords in a script but you will have to encrypt and obfuscate the script so that it cannot be read. In order to successfully encrypt and obfuscate a shell script and actually have that script be executable, try copying and pasting it here:

On the above page, all you have to do is submit your script and give the script a proper name, then hit the download button. A zip file will be generated for you. Right click on the download link and copy the URL you're provided. Then, go to your UNIX box and perform the following steps.


1. wget link-to-the-zip-file
2. unzip the-newly-downloaded-zip-file
3. cd /tmp/KingLazySHIELD
4. ./ /var/tmp/KINGLAZY/SHIELDX-(your-script-name) /home/(your-username) -force

What the above install command will do for you is:

  1. Install the encrypted version of your script in the directory /var/tmp/KINGLAZY/SHIELDX-(your-script-name).
  2. It'll place a link to this encrypted script in whichever directory you specify in replacement of /home/(your-username) - that way, it allows you to easily access the script without having to type the absolute path.
  3. Ensures NO ONE can modify the script - Any attempts to modify the encrypted script will render it inoperable...until those attempts are stopped or removed. It can even be configured to notify you whenever someone tries to do anything with the script other than run it...i.e. hacking or modification attempts.
  4. Ensures absolutely NO ONE can make copies of it. No one can copy your script to a secluded location and try to screw around with it to see how it works. All copies of the script must be links to the original location which you specified during install (step 4).


This does not work for interactive scripts that prompts and waits on the user for a response. The values that are expected from the user should be hard-coded into the script. The encryption ensures no one can actually see those values so you need not worry about that.


The solution provided in this post answers your problem in the sense that it encrypts the actual script containing the password that you wanted to have encrypted. You get to leave the password as is (unencrypted) but the script that the password is in is so deeply obfuscated and encrypted that you can rest assured no one will be able to see it. And if attempts are made to try to pry into the script, you will receive email notifications about them.

Google Chrome redirecting localhost to https

I am facing the same problem but only in Chrome Canary and searching a solution I've found this post.

one of the next versions of Chrome is going to force all domains ending on .dev (and .foo) to be redirected to HTTPs via a preloaded HTTP Strict Transport Security (HSTS) header.

{ "name": "dev", "include_subdomains": true, "mode": "force-https" },
{ "name": "foo", "include_subdomains": true, "mode": "force-https" },

So, change your domains.

How to run DOS/CMD/Command Prompt commands from VB.NET?

Imports System.IO
Public Class Form1
    Public line, counter As String
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        counter += 1
        If TextBox1.Text = "" Then
            MsgBox("Enter a DNS address to ping")
            'line = ":start" + vbNewLine
            'line += "ping " + TextBox1.Text
            Dim StreamToWrite As StreamWriter
            StreamToWrite = New StreamWriter("C:\Desktop\Ping" + counter + ".bat")
            StreamToWrite.Write(":start" + vbNewLine + _
                                "Ping -t " + TextBox1.Text)
            Dim p As New System.Diagnostics.Process()
            p.StartInfo.FileName = "C:\Desktop\Ping" + counter + ".bat"
        End If
    End Sub
End Class

This works as well

ssh connection refused on Raspberry Pi

Apparently, the SSH server on Raspbian is now disabled by default. If there is no server listening for connections, it will not accept them. You can manually enable the SSH server according to this tutorial :

As of the November 2016 release, Raspbian has the SSH server disabled by default.

There are now multiple ways to enable it. Choose one:

From the desktop

  1. Launch Raspberry Pi Configuration from the Preferences menu
  2. Navigate to the Interfaces tab
  3. Select Enabled next to SSH
  4. Click OK

From the terminal with raspi-config

  1. Enter sudo raspi-config in a terminal window
  2. Select Interfacing Options
  3. Navigate to and select SSH
  4. Choose Yes
  5. Select Ok
  6. Choose Finish

Start the SSH service with systemctl

sudo systemctl enable ssh
sudo systemctl start ssh

On a headless Raspberry Pi

For headless setup, SSH can be enabled by placing a file named ssh, without any extension, onto the boot partition of the SD card. When the Pi boots, it looks for the ssh file. If it is found, SSH is enabled, and the file is deleted. The content of the file does not matter: it could contain text, or nothing at all.

How do search engines deal with AngularJS applications?

Angular's own website serves simplified content to search engines:

Say your Angular app is consuming a Node.js/Express-driven JSON api, like /api/path/to/resource. Perhaps you could redirect any requests with ?_escaped_fragment_ to /api/path/to/resource.html, and use content negotiation to render an HTML template of the content, rather than return the JSON data.

The only thing is, your Angular routes would need to match 1:1 with your REST API.

EDIT: I'm realizing that this has the potential to really muddy up your REST api and I don't recommend doing it outside of very simple use-cases where it might be a natural fit.

Instead, you can use an entirely different set of routes and controllers for your robot-friendly content. But then you're duplicating all of your AngularJS routes and controllers in Node/Express.

I've settled on generating snapshots with a headless browser, even though I feel that's a little less-than-ideal.

Converting string to number in javascript/jQuery

Although this is an old post, I thought that a simple function can make the code more readable and keeps with jQuery chaining code-style:

String.prototype.toNum = function(){
    return parseInt(this, 10);

can be used with jQuery:

var padding_top = $('#some_div').css('padding-top'); //string: "10px"
var padding_top = $('#some_div').css('padding-top').toNum(); //number: 10`

or with any String object:

"123".toNum(); //123 (number)`

Calculating sum of repeated elements in AngularJS ng-repeat

This is my solution

sweet and simple custom filter:

(but only related to simple sum of values, not sum product, I've made up sumProduct filter and appended it as edit to this post).

angular.module('myApp', [])

    .filter('total', function () {
        return function (input, property) {
            var i = input instanceof Array ? input.length : 0;
// if property is not defined, returns length of array
// if array has zero length or if it is not an array, return zero
            if (typeof property === 'undefined' || i === 0) {
                return i;
// test if property is number so it can be counted
            } else if (isNaN(input[0][property])) {
                throw 'filter total can count only numeric values';
// finaly, do the counting and return total
            } else {
                var total = 0;
                while (i--)
                    total += input[i][property];
                return total;

JS Fiddle

EDIT: sumProduct

This is sumProduct filter, it accepts any number of arguments. As a argument it accepts name of the property from input data, and it can handle nested property (nesting marked by dot: property.nested);

  • Passing zero argument returns length of input data.
  • Passing just one argument returns simple sum of values of that properties.
  • Passing more arguments returns sum of products of values of passed properties (scalar sum of properties).

here's JS Fiddle and the code

angular.module('myApp', [])
    .filter('sumProduct', function() {
        return function (input) {
            var i = input instanceof Array ? input.length : 0;
            var a = arguments.length;
            if (a === 1 || i === 0)
                return i;

            var keys = [];
            while (a-- > 1) {
                var key = arguments[a].split('.');
                var property = getNestedPropertyByKey(input[0], key);
                if (isNaN(property))
                    throw 'filter sumProduct can count only numeric values';

            var total = 0;
            while (i--) {
                var product = 1;
                for (var k = 0; k < keys.length; k++)
                    product *= getNestedPropertyByKey(input[i], keys[k]);
                total += product;
            return total;

            function getNestedPropertyByKey(data, key) {
                for (var j = 0; j < key.length; j++)
                    data = data[key[j]];
                return data;

JS Fiddle

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

What you should not do do (especially when working on a shared project)

Ok, after had the same issue and after reading some answers here and other places. it seems that putting external lib into WEB-INF/lib is not that good idea as it pollute webapp/JRE libs with server-specific libraries - for more information check this answer"

Another solution that i do NOT recommend is: to copy it into tomcat/lib folder. although this may work, it will be hard to manage dependency for a shared(git for example) project.

Good solution 1

Create vendor folder. put there all your external lib. then, map this folder as dependency to your project. in eclipse you need to

  1. add your folder to the build path
    1. Project Properties -> Java build path
    2. Libraries -> add external lib or any other solution to add your files/folder
  2. add your build path to deployment Assembly (reference)
    1. Project Properties -> Deployment Assembly
    2. Add -> Java Build Path Entries
    3. You should now see the list of libraries on your build path that you can specify for inclusion into your finished WAR.
    4. Select the ones you want and hit Finish.

Good solution 2

Use maven (or any alternative) to manage project dependency

Find if a textbox is disabled or not using jquery

 if($("element_selector").attr('disabled') || $("element_selector").prop('disabled'))

    // code when element is disabled


How to resolve TypeError: Cannot convert undefined or null to object

Generic answer

This error is caused when you call a function that expects an Object as its argument, but pass undefined or null instead, like for example

Object.assign(window.UndefinedVariable, {})

As that is usually by mistake, the solution is to check your code and fix the null/undefined condition so that the function either gets a proper Object, or does not get called at all.

Object.keys({'key': 'value'})
if (window.UndefinedVariable) {
    Object.assign(window.UndefinedVariable, {})

Answer specific to the code in question

The line if (obj === 'null') { return null;} // null unchanged will not evaluate when given null, only if given the string "null". So if you pass the actual null value to your script, it will be parsed in the Object part of the code. And Object.keys(null) throws the TypeError mentioned. To fix it, use if(obj === null) {return null} - without the qoutes around null.

count number of lines in terminal output

"abcd4yyyy" | grep 4 -c gives the count as 1

Rebuild all indexes in a Database

Daniel's script appears to be a good all encompassing solution, but even he admitted that his laptop ran out of memory. Here is an option I came up with. I based my procedure off of Mohammad Nizamuddin's post on TechNet. I added an initial cursor loop that pulls all the database names into a temporary table and then uses that to pull all the base table names from each of those databases.

You can optionally pass the fill factor you would prefer and specify a target database if you do not want to re-index all databases.

-- Name:  sp_RebuildAllIndexes
-- Arguements:  [Fill Factor], [Target Database name]
-- Purpose:  Loop through all the databases on a server and
--           compile a list of all the table within them.
--           This list is then used to rebuild indexes for
--           all the tables in all the database.  Optionally,
--           you may pass a specific database name if you only
--           want to reindex that target database.
CREATE PROCEDURE sp_RebuildAllIndexes(
    @FillFactor     INT = 90,
    @TargetDatabase NVARCHAR(100) = NULL)
        DECLARE @TablesToReIndex TABLE (
            TableName VARCHAR(200)
        DECLARE @DbName VARCHAR(50);
        DECLARE @TableSelect VARCHAR(MAX);
        DECLARE @DatabasesToIndex CURSOR;

        IF ISNULL( @TargetDatabase, '' ) = ''
          SET @DatabasesToIndex = CURSOR
              FROM   master..sysdatabases
          SET @DatabasesToIndex = CURSOR
              FROM   master..sysdatabases
              WHERE  NAME = @TargetDatabase

        OPEN DatabasesToIndex

        FETCH NEXT FROM DatabasesToIndex INTO @DbName

        WHILE @@FETCH_STATUS = 0
                SET @TableSelect = 'INSERT INTO @TablesToReIndex SELECT CONCAT(TABLE_CATALOG, ''.'', TABLE_SCHEMA, ''.'', TABLE_NAME) AS TableName FROM '
                                   + @DbName
                                   + '.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''base table''';

                EXEC sp_executesql

                FETCH NEXT FROM DatabasesToIndex INTO @DbName

        CLOSE DatabasesToIndex

        DEALLOCATE DatabasesToIndex

        DECLARE @TableName VARCHAR(255)
        DECLARE TableCursor CURSOR FOR
            SELECT TableName
            FROM   @TablesToReIndex

        OPEN TableCursor

        FETCH NEXT FROM TableCursor INTO @TableName

        WHILE @@FETCH_STATUS = 0
                DBCC DBREINDEX(@TableName, ' ', @FillFactor)

                FETCH NEXT FROM TableCursor INTO @TableName

        CLOSE TableCursor

        DEALLOCATE TableCursor

How to reset the bootstrap modal when it gets closed and open it fresh again?

Using BS 3.3.7

$("#yourModal").on('', function () {
    $(this).data('bs.modal', null); // will clear all element inside modal

Using Bootstrap Tooltip with AngularJS

easiest way , add $("[data-toggle=tooltip]").tooltip(); to the concerned controller.

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")

edit: use input in python 3.2 instead of raw_input

How to turn a vector into a matrix in R?

Just use matrix:

matrix(vec,nrow = 7,ncol = 7)

One advantage of using matrix rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow argument in matrix.

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

please check the space available on drive where the db is stored. in my case it was stopped the service due to less space on drive.

Difference between pre-increment and post-increment in a loop?

The question is:

Is there a difference in ++i and i++ in a for loop?

The answer is: No.

Why does each and every other answer have to go into detailed explanations about pre and post incrementing when this is not even asked?

This for-loop:

for (int i = 0; // Initialization
     i < 5;     // Condition
     i++)       // Increment

Would translate to this code without using loops:

int i = 0; // Initialization

if (i < 5) // Condition

   i++ or ++i; // Increment

   goto loopStart;

Now does it matter if you put i++ or ++i as increment here? No it does not as the return value of the increment operation is insignificant. i will be incremented AFTER the code's execution that is inside the for loop body.

CSS get height of screen resolution

Use height and width in percentage.

For example:

width: 80%;
height: 80%;

Illegal character in path at index 16

There's an illegal character at index 16. I'd say it doesn't like the space in the path. You can percent encode special characters like spaces. Replace it with a %20 in this case.

The question I linked to above suggests using URLEncoder:

String thePath = "file://E:/Program Files/IBM/SDP/runtimes/base";
thePath = URLEncoder.encode(thePath, "UTF-8"); 

Saving excel worksheet to CSV files with filename+worksheet name using VB

I think this is what you want...

Sub SaveWorksheetsAsCsv()

Dim WS As Excel.Worksheet
Dim SaveToDirectory As String

Dim CurrentWorkbook As String
Dim CurrentFormat As Long

CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook
SaveToDirectory = "H:\test\"

For Each WS In Application.ActiveWorkbook.Worksheets
    WS.SaveAs SaveToDirectory & WS.Name, xlCSV

Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
Application.DisplayAlerts = True
' Temporarily turn alerts off to prevent the user being prompted
'  about overwriting the original file.

End Sub

Can I access a form in the controller?

Yes, you can access a form in the controller (as stated in the docs).

Except when your form is not defined in the controller scope and is defined in a child scope instead.

Basically, some angular directives, such as ng-if, ng-repeat or ng-include, will create an isolated child scope. So will any custom directives with a scope: {} property defined. Probably, your foundation components are also in your way.

I had the same problem when introducing a simple ng-if around the <form> tag.

See these for more info:

Note: I suggest you re-write your question. The answer to your question is yes but your problem is slightly different:

Can I access a form in a child scope from the controller?

To which the answer would simply be: no.

Convert list of ASCII codes to string (byte array) in Python

struct.pack('B' * len(integers), *integers)

*sequence means "unpack sequence" - or rather, "when calling f(..., *args ,...), let args = sequence".

VB.NET - Click Submit Button on Webbrowser page

Just follow two steps for clicking a any button using code.

  1. focus the button or element which you want to click

    WebBrowser1.Document.GetElementById("place id here").Focus()

  2. simulate mouse click using this following code


How to use Apple's new .p8 certificate for APNs in firebase console

I was able to do this by selecting "All" located under the "Keys" header from the left column

enter image description here

Then I clicked the plus button in the top right corner to add a new key

enter image description here

Enter a name for your key and check "APNs"

enter image description here

Then scroll down and select Continue. You will then be brought to a screen presenting you with the option to download your .p8 now or later. In my case, I was presented with a warning that it could only be downloaded once so keep the file safe.

Find Locked Table in SQL Server


When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:

SELECT object_name(16003073)


There is another proc provided by microsoft which reports objects without the ID translation :

How do you obtain a Drawable object from a resource id in android package?

From API 21 `getDrawable(int id)` is deprecated

So now you need to use

ResourcesCompat.getDrawable(context.getResources(), R.drawable.img_user, null)

But Best way to do is :

- You should create one common class for getting drawable and colors because if in future have any deprecation then you no need to do changes everywhere in your project.You just change in this method
object ResourceUtils {
    fun getColor(context: Context, color: Int): Int {
        return ResourcesCompat.getColor(context.getResources(), color, null)

    fun getDrawable(context: Context, drawable: Int): Drawable? {
        return ResourcesCompat.getDrawable(context.getResources(), drawable, null)

use this method like :

Drawable img=ResourceUtils.getDrawable(context, R.drawable.img_user)

Bootstrap Columns Not Working

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="col-md-4">  
                    <a href="">About</a>
                <div class="col-md-4">
                    <img src="image.png">
                <div class="col-md-4"> 
                    <a href="#myModal1" data-toggle="modal">SHARE</a>

You need to nest the interior columns inside of a row rather than just another column. It offsets the padding caused by the column with negative margins.

A simpler way would be

<div class="container">
   <div class="row">
       <div class="col-md-4">  
          <a href="">About</a>
       <div class="col-md-4">
          <img src="image.png">
       <div class="col-md-4"> 
           <a href="#myModal1" data-toggle="modal">SHARE</a>

Using Python, find anagrams for a list of words

here is the impressive solution.

funct alphabet_count_mapper:

for each word in the file/list

1.create a dictionary of alphabets/characters with initial count as 0.

2.keep count of all the alphabets in the word and increment the count in the above alphabet dict.

3.create alphabet count dict and return the tuple of the values of alphabet dict.

funct anagram_counter:

1.create a dictionary with alphabet count tuple as key and the count of the number of occurences against it.

2.iterate over the above dict and if the value > 1, add the value to the anagram count.

    import sys
    words_count_map_dict = {}
    fobj = open(sys.argv[1],"r")
    words ='\n')[:-1]

    def alphabet_count_mapper(word):
        alpha_count_dict = dict(zip('abcdefghijklmnopqrstuvwxyz',[0]*26))
        for alpha in word:
            if alpha in alpha_count_dict.keys():
                alpha_count_dict[alpha] += 1
        return tuple(alpha_count_dict.values())

    def anagram_counter(words):
        anagram_count = 0
        for word in words:
            temp_mapper = alphabet_count_mapper(word)
            if temp_mapper in words_count_map_dict.keys():
                words_count_map_dict[temp_mapper] += 1
        for val in words_count_map_dict.values():
            if val > 1:
                anagram_count += val
        return anagram_count

    print anagram_counter(words)

run it with file path as command line argument

Converting HTML to XML

I was successful using tidy command line utility. On linux I installed it quickly with apt-get install tidy. Then the command:

tidy -q -asxml --numeric-entities yes source.html >file.xml

gave an xml file, which I was able to process with xslt processor. However I needed to set up xhtml1 dtds correctly.

This is their homepage: (and the legacy one: HTML Tidy)

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 


select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

How do I check if a cookie exists?

instead of the cookie variable you would just use document.cookie.split...

var cookie = 'cookie1=s; cookie1=; cookie2=test';_x000D_
var cookies = cookie.split('; ');_x000D_

Permission denied error while writing to a file in Python

To answer your first question: yes, if the file is not there Python will create it.

Secondly, the user (yourself) running the python script doesn't have write privileges to create a file in the directory.

How to prevent a click on a '#' link from jumping to top of page?

You could just pass an anchor tag without an href property, and use jQuery to do the required action:

<a class="foo">bar</a>

Checking whether the pip is installed?

$ which pip


 $ pip -V 

execute this command into your terminal. It should display the location of executable file eg. /usr/local/bin/pip and the second command will display the version if the pip is installed correctly.

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    []="section.value">{{ section.text }}</li>  


<ol class="viewer-nav"><li *ngFor="let section of sections""{{section.value}}">{{ section.text }}</li>  

See also :

Disable Transaction Log

If this is only for dev machines in order to save space then just go with simple recovery mode and you’ll be doing fine.

On production machines though I’d strongly recommend that you keep the databases in full recovery mode. This will ensure you can do point in time recovery if needed.

Also – having databases in full recovery mode can help you to undo accidental updates and deletes by reading transaction log. See below or more details.

How can I rollback an UPDATE query in SQL server 2005?

Read the log file (*.LDF) in sql server 2008

If space is an issue on production machines then just create frequent transaction log backups.

Delete empty rows

If you are trying to delete empty spaces , try using ='' instead of is null. Hence , if your row contains empty spaces , is null will not capture those records. Empty space is not null and null is not empty space.

Dec  Hex     Binary    Char-acter Description
0    00  00000000      NUL        null

32  20  00100000      Space       space

So I recommend:

delete  from foo_table  where bar = ''


delete  from foo_table  where bar = '' or bar is null 

#or even better , 

delete from foo_table where rtrim(ltrim(isnull(bar,'')))='';

jQuery check if <input> exists and has a value

You could do:

if($('.input1').length && $('.input1').val().length)

length evaluates to false in a condition, when the value is 0.

Unable to get spring boot to automatically create database schema

In my case the tables were not getting created automatically even though I was using JPArepository. After adding the below property in my springboot app file the tables are now getting created automatically. spring.jpa.hibernate.ddl-auto=update

Notify ObservableCollection when Item changes

All the solutions here are correct,but they are missing an important scenario in which the method Clear() is used, which doesn't provide OldItems in the NotifyCollectionChangedEventArgs object.

this is the perfect ObservableCollection .

public delegate void ListedItemPropertyChangedEventHandler(IList SourceList, object Item, PropertyChangedEventArgs e);
public class ObservableCollectionEX<T> : ObservableCollection<T>
    #region Constructors
    public ObservableCollectionEX() : base()
        CollectionChanged += ObservableCollection_CollectionChanged;
    public ObservableCollectionEX(IEnumerable<T> c) : base(c)
        CollectionChanged += ObservableCollection_CollectionChanged;
    public ObservableCollectionEX(List<T> l) : base(l)
        CollectionChanged += ObservableCollection_CollectionChanged;


    public new void Clear()
        foreach (var item in this)            
            if (item is INotifyPropertyChanged i)                
                i.PropertyChanged -= Element_PropertyChanged;            
    private void ObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        if (e.OldItems != null)
            foreach (var item in e.OldItems)                
                if (item != null && item is INotifyPropertyChanged i)                    
                    i.PropertyChanged -= Element_PropertyChanged;

        if (e.NewItems != null)
            foreach (var item in e.NewItems)                
                if (item != null && item is INotifyPropertyChanged i)
                    i.PropertyChanged -= Element_PropertyChanged;
                    i.PropertyChanged += Element_PropertyChanged;
    private void Element_PropertyChanged(object sender, PropertyChangedEventArgs e) => ItemPropertyChanged?.Invoke(this, sender, e);

    public ListedItemPropertyChangedEventHandler ItemPropertyChanged;


How to make a owl carousel with arrows instead of next previous

If you're using Owl Carousel 2, then you should use the following:

     items : 4,
     loop  : true,
     margin : 30,
     nav    : true,
     smartSpeed :900,
     navText : ["<i class='fa fa-chevron-left'></i>","<i class='fa fa-chevron-right'></i>"]

How does C compute sin() and other math functions?

Computing sine/cosine/tangent is actually very easy to do through code using the Taylor series. Writing one yourself takes like 5 seconds.

The whole process can be summed up with this equation here:

sin and cost expansion

Here are some routines I wrote for C:

double _pow(double a, double b) {
    double c = 1;
    for (int i=0; i<b; i++)
        c *= a;
    return c;

double _fact(double x) {
    double ret = 1;
    for (int i=1; i<=x; i++) 
        ret *= i;
    return ret;

double _sin(double x) {
    double y = x;
    double s = -1;
    for (int i=3; i<=100; i+=2) {
        s *= -1;
    return y;
double _cos(double x) {
    double y = 1;
    double s = -1;
    for (int i=2; i<=100; i+=2) {
        s *= -1;
    return y;
double _tan(double x) {
     return (_sin(x)/_cos(x));  

Twitter Bootstrap alert message close and open again

Data-dismiss completely removes the element. Use jQuery's .hide() method instead.

The fix-it-quick method:

Using inline javascript to hide the element onclick like this:

<div class="alert" style="display: none"> 
    <a class="close" onclick="$('.alert').hide()">×</a>  
    <strong>Warning!</strong> Best check yo self, you're not looking too good.  

<a href="#" onclick="$('alert').show()">show</a>

This should however only be used if you are lazy (which is no good thing if you want an maintainable app).

The do-it-right method:

Create a new data attribute for hiding an element.


    $("[data-hide]").on("click", function(){
        $("." + $(this).attr("data-hide")).hide()
        // -or-, see below
        // $(this).closest("." + $(this).attr("data-hide")).hide()

and then change data-dismiss to data-hide in the markup. Example at jsfiddle.

$("." + $(this).attr("data-hide")).hide()

This will hide all elements with the class specified in data-hide, i.e: data-hide="alert" will hide all elements with the alert class.

Xeon06 provided an alternative solution:

$(this).closest("." + $(this).attr("data-hide")).hide()

This will only hide the closest parent element. This is very useful if you don't want to give each alert a unique class. Please note that, however, you need to place the close button within the alert.

Definition of .closest from jquery doc:

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Maximum on http header values?

If you are going to use any DDOS provider like Akamai, they have a maximum limitation of 8k in the response header size. So essentially try to limit your response header size below 8k.

What does "<>" mean in Oracle

It (<>) is a function that is used to compare values in database table.

!= (Not equal to) functions the same as the <> (Not equal to) comparison operator.

Python 3 - Encode/Decode vs Bytes/Str

Neither is better than the other, they do exactly the same thing. However, using .encode() and .decode() is the more common way to do it. It is also compatible with Python 2.

jQuery: more than one handler for same event

There is a workaround to guarantee that one handler happens after another: attach the second handler to a containing element and let the event bubble up. In the handler attached to the container, you can look at and do something if it's the one you're interested in.

Crude, maybe, but it definitely should work.

How to get the current working directory using python 3?

Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded. Ref: docs

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

Doc ref: link

Plotting a 3d cube, a sphere and a vector in Matplotlib

My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)

# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)

# tails of the arrows
tails= np.zeros(len(bvecs))

# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
          length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)


ax.set_title('b-vectors on unit sphere')

Convert java.util.Date to String

Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);

How to put a UserControl into Visual Studio toolBox

Basic qustion if you are using generics in your base control. If yes:

lets say we have control:

public class MyComboDropDown : ComboDropDownComon<MyType>
    public MyComboDropDown() { }

MyComboDropDown will not allow to open designer on it and will be not shown in Toolbox. Why? Because base control is not already compiled - when MyComboDropDown is complied. You can modify to this:

public class MyComboDropDown : MyComboDropDownBase
    public MyComboDropDown() { }

public class MyComboDropDownBase : ComboDropDownComon<MyType>


Than after rebuild, and reset toolbox it should be able to see MyComboDropDown in designer and also in Toolbox

Extend contigency table with proportions (percentages)

Here's a tidyverse version:


($cut)) %>% rename(Count=1,Freq=2) %>% mutate(Perc=100*Freq/sum(Freq)))

Or if you want a handy function:

getPercentages <- function(df, colName) {
  df.cnt <- df %>% select({{colName}}) %>% 
    table() %>% %>% 
    rename({{colName}} :=1, Freq=2) %>% 

Now you can do:

diamonds %>% getPercentages(cut)

or this:

df=diamonds %>% group_by(cut) %>% group_modify(~.x %>% getPercentages(clarity))

How can I suppress the newline after a print statement?

Because python 3 print() function allows end="" definition, that satisfies the majority of issues.

In my case, I wanted to PrettyPrint and was frustrated that this module wasn't similarly updated. So i made it do what i wanted:

from pprint import PrettyPrinter

class CommaEndingPrettyPrinter(PrettyPrinter):
    def pprint(self, object):
        self._format(object, self._stream, 0, 0, {}, 0)
        # this is where to tell it what you want instead of the default "\n"

def comma_ending_prettyprint(object, stream=None, indent=1, width=80, depth=None):
    """Pretty-print a Python object to a stream [default is sys.stdout] with a comma at the end."""
    printer = CommaEndingPrettyPrinter(
        stream=stream, indent=indent, width=width, depth=depth)

Now, when I do:

comma_ending_prettyprint(row, stream=outfile)

I get what I wanted (substitute what you want -- Your Mileage May Vary)

How do I convert a String to an int in Java?

Some of the ways to convert String into Int are as follows:

  1. You can use Integer.parseInt():

    String test = "4568";
    int new = Integer.parseInt(test);
  2. Also you can use Integer.valueOf():

    String test = "4568";
    int new = Integer.valueOf(test);

Pushing to Git returning Error Code 403 fatal: HTTP request failed

To definitely be able to login using https protocol, you should first set your authentication credential to the git Remote URI:

git remote set-url origin https://[email protected]/user/repo.git

Then you'll be asked for a password when trying to git push.

In fact, this is on the http authentication format. You could set a password too:

https://youruser:[email protected]/user/repo.git

You should be aware that if you do this, your github password will be stored in plaintext in your .git directory, which is obviously undesirable.

Multiline TextBox multiple newline

I had the same problem. If I add one Environment.Newline I get one new line in the textbox. But if I add two Environment.Newline I get one new line. In my web app I use a whitespace modul that removes all unnecessary white spaces. If i disable this module I get two new lines in my textbox. Hope that helps.

Scroll event listener javascript

For those who found this question hoping to find an answer that doesn't involve jQuery, you hook into the window "scroll" event using normal event listening. Say we want to add scroll listening to a number of CSS-selector-able elements:

// what should we do when scrolling occurs
var runOnScroll =  function(evt) {
  // not the most exciting thing, but a thing nonetheless

// grab elements as array, rather than as NodeList
var elements = document.querySelectorAll("...");
elements =;

// and then make each element do something on scroll
elements.forEach(function(element) {
  window.addEventListener("scroll", runOnScroll, {passive: true});

(Using the passive attribute to tell the browser that this event won't interfere with scrolling itself)

For bonus points, you can give the scroll handler a lock mechanism so that it doesn't run if we're already scrolling:

// global lock, so put this code in a closure of some sort so you're not polluting.
var locked = false;
var lastCall = false;

var runOnScroll =  function(evt) {
  if(locked) return;

  if (lastCall) clearTimeout(lastCall);
  lastCall = setTimeout(() => {
    // you do this because you want to handle the last
    // scroll event, even if it occurred while another
    // event was being processed.
  }, 200);

  // ...your code goes here...

  locked = false;

How to set a value of a variable inside a template code?

There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates).
Because of this, the recommended way to change any variable is via touching the Python code.

Prevent flex items from overflowing a container

One easy solution is to use overflow values other than visible to make the text flex basis width reset as expected.

  1. Here with value auto the text wraps as expected and the article content does not overflow main container.

  2. Also, the article flex value must either have a auto basis AND be able to shrink, OR, only grow AND explicit 0 basis

main, aside, article {_x000D_
  margin: 10px;_x000D_
  border: solid 1px #000;_x000D_
  border-bottom: 0;_x000D_
  height: 50px;_x000D_
  overflow: auto; /* 1. overflow not `visible` */_x000D_
main {_x000D_
  display: flex;_x000D_
aside {_x000D_
  flex: 0 0 200px;_x000D_
article {_x000D_
  flex: 1 1 auto; /* 2. Allow auto width content to shrink */_x000D_
  /* flex: 1 0 0; /* Or, explicit 0 width basis that grows */_x000D_
  <aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
  <article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_

How to create a stopwatch using JavaScript?

well after a few modification of the code provided by mace,i ended up building a stopwatch.

  <!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    #center {
     margin: 30%  30%;
     font-family: tahoma;
    .stopwatch {
         border:1px solid #000;
         background-color: #eee;
         text-align: center;
         height: 230px;
         overflow: hidden;
     .stopwatch span{
         display: block;
         font-size: 100px;
     .stopwatch p{
         display: inline-block;
         font-size: 40px;
     .stopwatch a{
         color :#000;
         text-decoration: none;
         padding: 12px 14px;
         border: 1px solid #000;
      <div id="center">
            <div class="timer stopwatch"></div>

      const Stopwatch = function(elem, options) {
        let timer = createTimer(),
          startButton = createButton("start", start),
          stopButton = createButton("stop", stop),
          resetButton = createButton("reset", reset),
          hrs = 0,
          min = 0;

        // default options
        options = options || {};
        options.delay = options.delay || 1;

        // append elements

        // initialize

        // private functions
        function createTimer() {
          return document.createElement("span");

        function createButton(action, handler) {
          if (action !== "reset") {
            let a = document.createElement("a");
            a.href = "#" + action;
            a.innerHTML = action;
            a.addEventListener("click", function(event) {
            return a;
          } else if (action === "reset") {
            let a = document.createElement("a");
            a.href = "#" + action;
            a.innerHTML = action;
            a.addEventListener("click", function(event) {
            return a;

        function start() {
          if (!interval) {
            offset =;
            interval = setInterval(update, options.delay);

        function stop() {
          if (interval) {
            interval = null;

        function reset() {
          clock = 0;

        function clean() {
          min = 0;
          hrs = 0;
          clock = 0;

        function update() {
          clock += delta();

        function render() {
          if (Math.floor(clock / 1000) === 60) {
            if (min === 60) {
              min = 0;
          timer.innerHTML =
            hrs + "<p>hrs</p>" + min + "<p>min</p>" + Math.floor(clock / 1000)+ "<p>sec</p>";

        function delta() {
          var now =,
            d = now - offset;

          offset = now;
          return d;

      // Initiating the Stopwatch
      var elems = document.getElementsByClassName("timer");

      for (var i = 0, len = elems.length; i < len; i++) {
        new Stopwatch(elems[i]);

Write string to text file and ensure it always overwrites the existing content.

Use the File.WriteAllText method. It creates the file if it doesn't exist and overwrites it if it exists.

Parse date string and change format

datetime module could help you with that:

datetime.datetime.strptime(date_string, format1).strftime(format2)

For the specific example you could do

>>> datetime.datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')

Move entire line up and down in Vim

This worked for me:

BTW, if you want to use ALT+some_key and your terminal (urxvt does this) refuses to comply, you should enter something like this in your .vimrc:

" For moving lines (^] is a special character; use <M-k> and <M-j> if it works)
nnoremap ^]k mz:m-2<CR>`z==
inoremap ^]j <Esc>:m+<CR>==gi
inoremap ^]k <Esc>:m-2<CR>==gi
vnoremap ^]j :m'>+<CR>gv=`<my`>mzgv`yo`z
nnoremap ^]j mz:m+<CR>`z==
vnoremap ^]k :m'<-2<CR>gv=`>my`<mzgv`yo`z

where ^] is a single character that represents the ALT key. To input that character, use C+v, Esc in Vim (C+q, Esc on Windows).

Revert to Eclipse default settings

you need to do the process for all individual languages you work on...

enter image description here

How to avoid precompiled headers

Right click project solution

Properties -> Configuration Properties -> C/C++ -> Precompiled Headers

  1. Click on "Precompiled Headers" change to "Not Using Precompiled Headers".

  2. Erase the "pch.h"/"stdafx.h" field in "Precompiled Header File" for the EOF error at the end of the build for the project.

  3. Then you can feel free to delete the pch./stdafx. files in your project

log4j:WARN No appenders could be found for logger (running jar file, not web app)

Move Your file into the src folder. Open Windows explorer, browse to the directory where your project resides in. Browse to bin directory and delete all the folders with in it.

Now in eclipse click project---->clean---->OK

This would force it to build the project again,all the contents delete from bin directory will be recreated.

I took while to figure this out. At times directly clicking clean doesn't work

Download data url file

Here is a pure JavaScript solution I tested working in Firefox and Chrome but not in Internet Explorer:

function downloadDataUrlFromJavascript(filename, dataUrl) {

    // Construct the 'a' element
    var link = document.createElement("a"); = filename; = "_blank";

    // Construct the URI
    link.href = dataUrl;

    // Cleanup the DOM
    delete link;

Cross-browser solutions found up until now:

downloadify -> Requires Flash

databounce -> Tested in IE 10 and 11, and doesn't work for me. Requires a servlet and some customization. (Incorrectly detects navigator. I had to set IE in compatibility mode to test, default charset in servlet, JavaScript options object with correct servlet path for absolute paths...) For non-IE browsers, it opens the file in the same window.

download.js -> Another library similar but not tested. Claims to be pure JavaScript, not requiring servlet nor Flash, but doesn't work on IE <= 9.

How to allow only one radio button to be checked?

Add "name" attribute and keep the name same for all the radio buttons in a form.


<input type="radio" name="test" value="value1"> Value 1
<input type="radio" name="test" value="value2"> Value 2
<input type="radio" name="test" value="value3"> Value 3

Hope that would help.

How to change icon on Google map marker

Manish, Eden after your suggestion: here is the code. But still showing the red(Default) icon.

<script type="text/javascript" src=""></script>

<script type="text/javascript">
var markers = [
            "title": 'This is title',
            "lat": '-37.801578',
            "lng": '145.060508',
        "icon": '',
            "description": 'Vikash Rathee. <br/><a href="">Pin Code by City</a>'
<script type="text/javascript">
    window.onload = function () {
        var mapOptions = {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            zoom: 10,
            flat: true,
            styles: [ { "stylers": [ { "hue": "#4bd6bf" }, { "gamma": "1.58" } ] } ],
            mapTypeId: google.maps.MapTypeId.ROADMAP
        var infoWindow = new google.maps.InfoWindow();
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
        for (i = 0; i < markers.length; i++) {
            var data = markers[i]
            var myLatlng = new google.maps.LatLng(, data.lng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
        icon: markers[i][3],
                title: data.title
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
          , marker);
            })(marker, data);

<div id="dvMap" style="width: 100%; height: 100%">

List files in local git repo?

git ls-tree --full-tree -r HEAD and git ls-files return all files at once. For a large project with hundreds or thousands of files, and if you are interested in a particular file/directory, you may find more convenient to explore specific directories. You can do it by obtaining the ID/SHA-1 of the directory that you want to explore and then use git cat-file -p [ID/SHA-1 of directory]. For example:

git cat-file -p 14032aabd85b43a058cfc7025dd4fa9dd325ea97
100644 blob b93a4953fff68df523aa7656497ee339d6026d64    glyphicons-halflings-regular.eot
100644 blob 94fb5490a2ed10b2c69a4a567a4fd2e4f706d841    glyphicons-halflings-regular.svg
100644 blob 1413fc609ab6f21774de0cb7e01360095584f65b    glyphicons-halflings-regular.ttf
100644 blob 9e612858f802245ddcbf59788a0db942224bab35    glyphicons-halflings-regular.woff
100644 blob 64539b54c3751a6d9adb44c8e3a45ba5a73b77f0    glyphicons-halflings-regular.woff2

In the example above, 14032aabd85b43a058cfc7025dd4fa9dd325ea97 is the ID/SHA-1 of the directory that I wanted to explore. In this case, the result was that four files within that directory were being tracked by my Git repo. If the directory had additional files, it would mean those extra files were not being tracked. You can add files using git add <file>... of course.

How to escape special characters in building a JSON string?

Most of these answers either does not answer the question or is unnecessarily long in the explanation.

OK so JSON only uses double quotation marks, we get that!

I was trying to use JQuery AJAX to post JSON data to server and then later return that same information. The best solution to the posted question I found was to use:

var d = {
    name: 'whatever',
    address: 'whatever',
    DOB: '01/01/2001'
    type: "POST",
    url: 'some/url',
    dataType: 'json',
    data: JSON.stringify(d),

This will escape the characters for you.

This was also suggested by Mark Amery, Great answer BTW

Hope this helps someone.

Using Colormaps to set color of line in matplotlib

I thought it would be beneficial to include what I consider to be a more simple method using numpy's linspace coupled with matplotlib's cm-type object. It's possible that the above solution is for an older version. I am using the python 3.4.3, matplotlib 1.4.3, and numpy 1.9.3., and my solution is as follows.

import matplotlib.pyplot as plt

from matplotlib import cm
from numpy import linspace

start = 0.0
stop = 1.0
number_of_lines= 1000
cm_subsection = linspace(start, stop, number_of_lines) 

colors = [ cm.jet(x) for x in cm_subsection ]

for i, color in enumerate(colors):
    plt.axhline(i, color=color)

plt.ylabel('Line Number')

This results in 1000 uniquely-colored lines that span the entire cm.jet colormap as pictured below. If you run this script you'll find that you can zoom in on the individual lines.

cm.jet between 0.0 and 1.0 with 1000 graduations

Now say I want my 1000 line colors to just span the greenish portion between lines 400 to 600. I simply change my start and stop values to 0.4 and 0.6 and this results in using only 20% of the cm.jet color map between 0.4 and 0.6.

enter image description here

So in a one line summary you can create a list of rgba colors from a colormap accordingly:

colors = [ cm.jet(x) for x in linspace(start, stop, number_of_lines) ]

In this case I use the commonly invoked map named jet but you can find the complete list of colormaps available in your matplotlib version by invoking:

>>> from matplotlib import cm
>>> dir(cm)

Capturing multiple line output into a Bash variable

How about this, it will read each line to a variable and that can be used subsequently ! say myscript output is redirected to a file called myscript_output

awk '{while ( (getline var < "myscript_output") >0){print var;} close ("myscript_output");}'

Datetime in where clause

WHERE datetime_column >= '20081220 00:00:00.000'
  AND datetime_column < '20081221 00:00:00.000'

How to hide a div after some time period?

Here's a complete working example based on your testing. Compare it to what you have currently to figure out where you are going wrong.

    <title>Untitled Document</title> 
    <script type="text/javascript" src=""></script>
    <script type="text/javascript"> 
      $(document).ready( function() {
    <div id=deletesuccess > hiiiiiiiiiii </div> 

Can I use an image from my local file system as background in HTML?

background: url(../images/backgroundImage.jpg) no-repeat center center fixed;

this should help

How do I select an element that has a certain class?

The CSS :first-child selector allows you to target an element that is the first child element within its parent.

element:first-child { style_properties }
table:first-child { style_properties }

How can I change property names when serializing with

If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.

For example, if you have a class called MyCustomObject, that has a property called LongPropertyName, you can use a custom resolver like this…

public class CustomDataContractResolver : DefaultContractResolver
  public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();

  protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    var property = base.CreateProperty(member, memberSerialization);
    if (property.DeclaringType == typeof(MyCustomObject))
      if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
        property.PropertyName = "Short";
    return property;

Then call for serialization and supply the resolver:

 var result = JsonConvert.SerializeObject(myCustomObjectInstance,
                new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });

And the result will be shortened to {"Short":"prop value"} instead of {"LongPropertyName":"prop value"}

More info on custom resolvers here

How to run Ruby code from terminal?

You can run ruby commands in one line with the -e flag:

ruby -e "puts 'hi'"

Check the man page for more information.

Search for an item in a Lua list

function valid(data, array)
 local valid = {}
 for i = 1, #array do
  valid[array[i]] = true
 if valid[data] then
  return false
  return true

Here's the function I use for checking if data is in an array.

What's the best way to generate a UML diagram from Python source code?

vipera is a small application designer, and uml is included. You can see it in:


Best regards.

How can I define an interface for an array of objects with Typescript?

Use like this!

interface Iinput {
  label: string
  placeholder: string
  register: any
  type?: string
  required: boolean

// This is how it can be done

const inputs: Array<Iinput> = [
    label: "Title",
    placeholder: "Bought something",
    register: register,
    required: true,

TSQL How do you output PRINT in a user defined function?

Tip: generate error.

declare @Day int, @Config_Node varchar(50)

    set @Config_Node = 'value to trace'

    set @Day = @Config_Node

You will get this message:

Conversion failed when converting the varchar value 'value to trace' to data type int.

How to include a quote in a raw Python string

If you want to use double quotes in strings but not single quotes, you can just use single quotes as the delimiter instead:


If you need both kinds of quotes in your string, use a triple-quoted string:


If you want to include both kinds of triple-quoted strings in your string (an extremely unlikely case), you can't do it, and you'll have to use non-raw strings with escapes.

REST URI convention - Singular or plural name of resource while creating it


  • Simple - all urls start with the same prefix
  • Logical - orders/ gets an index list of orders.
  • Standard - Most widely adopted standard followed by the overwhelming majority of public and private APIs.

For example:

GET /resources - returns a list of resource items

POST /resources - creates one or many resource items

PUT /resources - updates one or many resource items

PATCH /resources - partially updates one or many resource items

DELETE /resources - deletes all resource items

And for single resource items:

GET /resources/:id - returns a specific resource item based on :id parameter

POST /resources/:id - creates one resource item with specified id (requires validation)

PUT /resources/:id - updates a specific resource item

PATCH /resources/:id - partially updates a specific resource item

DELETE /resources/:id - deletes a specific resource item

To the advocates of singular, think of it this way: Would you ask a someone for an order and expect one thing, or a list of things? So why would you expect a service to return a list of things when you type /order?

compilation error: identifier expected

You have not defined a method around your code.


public class details
    public static void main( String[] args )
        BufferedReader in = new BufferedReader(new InputStreamReader(;
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);

In this case, I have assumed that you want your code to be executed in the main method of the class. It is, of course, possible that this code goes in any other method.

CSS values using HTML5 data attribute

There is, indeed, prevision for such feature, look

This fiddle should work like what you need, but will not for now.

Unfortunately, it's still a draft, and isn't fully implemented on major browsers.

It does work for content on pseudo-elements, though.

How do I POST JSON data with cURL?

If you're testing a lot of JSON send/responses against a RESTful interface, you may want to check out the Postman plug-in for Chrome (which allows you to manually define web service tests) and its Node.js-based Newman command-line companion (which allows you to automate tests against "collections" of Postman tests.) Both free and open!

Removing the fragment identifier from AngularJS urls (# symbol)

Step 1: Inject the $locationProvider service into the app config's constructor

Step 2: Add code line $locationProvider.html5Mode(true) to the app config's constructor.

Step 3: in the container (landing, master, or layout) page, add html tag such as <base href="/"> inside the tag.

Step 4: remove all '#" for routing config from all anchor tags. For examples, href="#home" becomes href="home"; href="#about" becomes herf="about"; href="#contact" becomes href="contact"

 <ul class="nav navbar-nav">
     <li><a href="home">Home</a></li>
     <li><a href="about">About us</a></li>
     <li><a href="contact">Contact us</a></li>

DLL Load Library - Error Code 126

This can also happen when you're trying to load a DLL and that in turn needs another DLL which cannot be not found.

Change a Git remote HEAD to point to something besides master

Related to the question, I ended up here when searching for:

How do I make a local repo aware of a changed default branch on GitHub

For completeness, adding the answer:

git remote set-head origin -a

Target a css class inside another css class

I use div instead of tables and am able to target classes within the main class, as below:


.main {
    .width: 800px;
    .margin: 0 auto;
    .text-align: center;
.main .table {
    width: 80%;
.main .row {
   / ***something ***/
.main .column {
    font-size: 14px;
    display: inline-block;
.main .left {
    width: 140px;
    margin-right: 5px;
    font-size: 12px;
.main .right {
    width: auto;
    margin-right: 20px;
    color: #fff;
    font-size: 13px;
    font-weight: normal;


<div class="main">
    <div class="table">
        <div class="row">
            <div class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>

If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:

.main #red { color: red; }

<div class="main">
    <div class="table">
        <div class="row">
            <div id="red" class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>

How to get access to HTTP header information in Spring MVC REST controller?

You can use the @RequestHeader annotation with HttpHeaders method parameter to gain access to all request headers:

@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
    // Use headers to get the information about all the request headers
    long contentLength = headers.getContentLength();
    // ...
    StreamSource source = new StreamSource(new StringReader(body));
    YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
    // ...

RecyclerView - Get view at particular position

To get specific view from recycler view list OR show error at edittext of recycler view.

private void popupErrorMessageAtPosition(int itemPosition) {

    RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(itemPosition);
    View view = viewHolder.itemView;
    EditText etDesc = (EditText) view.findViewById(;
    etDesc.setError("Error message here !");

How to check if $? is not equal to zero in unix shell scripting?

You don't need to test if $? is not 0. The shell provides && and || so you can easily branch based on implicit result of that test:

some_command && {
    # executes this block of code,
    # if some_command would result in:  $? -eq 0
} || {
    # executes this block of code,
    # if some_command would result in:  $? -ne 0

You can remove either branch, depending on what you want. So if you just want to test for failure (i.e. $? -ne 0):

some_command_returning_nonzero || {
    # executes this block of code when:     $? -ne 0
    # and nothing if the command succeeds:  $? -eq 0

However, the code you provided in the question works, as is. I'm confused that you got syntax errors & concluded that $? was a string. It's most likely that the errant code causing the syntax error was not provided with the question. This is especially evident because you claim that no one else's solutions work either. When this happens, you have to re-evaluate your assumptions.

NB: The code above may give confusing results if the code inside the braces returns an error. In that case simply use the if command instead, like this:

if some_command; then
    # executes this block of code,
    # if some_command would result in:  $? -eq 0
    # executes this block of code,
    # if some_command would result in:  $? -ne 0

List all kafka topics

You can try using the below two command and list all Kafka topic

  • bin/ --describe --zookeeper,,
  • bin/ --zookeeper,, --list

"No cached version... available for offline mode."

For mac, Uncheck Offline Work from Preference -> Build, Execution, Deployment -> Build Tools -> Gradle -> Global Gradle Settings

tip: cmd+, to open Preference via shortcut key

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

All in all, to save symbols that require 4 bytes you need to update characher-set and collation for utf8mb4:

  1. database table/column: alter table <some_table> convert to character set utf8mb4 collate utf8mb4_unicode_ci
  2. database server connection (see)

On my development enviromnt for #2 I prefer to set parameters on command line when starting the server: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci

btw, pay attention to Connector/J behavior with SET NAMES 'utf8mb4':

Do not issue the query set names with Connector/J, as the driver will not detect that the character set has changed, and will continue to use the character set detected during the initial connection setup.

And avoid setting characterEncoding parameter in connection url as it will override configured server encoding:

To override the automatically detected encoding on the client side, use the characterEncoding property in the URL used to connect to the server.

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

go to and download MySQL Connector/C. after getting the package, make a new directory 'mysql', uncompress the Mysql Connector file under directory mysql, then under mysql, make another empty directory 'build'.we will use 'build' to build MySQL Connector/C. cd build && cmake ../your-MySQL-Connector-source-dir make && make install after make install, you will get a directory named mysql under /usr/local. it contains all the headers and libs you need.go to this dirctory, and copy the headers and libs to corresponding locations.

Button Listener for button in fragment in android

Simply pass view object into onButtonClicked function. getView() does not seem to work as expected inside fragment. Try this code for your FragmentOne fragment

PS. you have redefined object view in your original FragmentOne code.

package com.example.fragmenttutorial;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentOne extends Fragment{

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_one, container, false);
        return view;

  protected void onButtonClicked(View view)
      if(view.getId() =={
          Fragment fragmentTwo = new FragmentTwo();

          fragmentTransaction.replace(, fragmentTwo);



How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.

2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

Difference between webdriver.Dispose(), .Close() and .Quit()

Difference between driver.close() & driver.quit()

driver.close – It closes the the browser window on which the focus is set.

driver.quit – It basically calls driver.dispose method which in turn closes all the browser windows and ends the WebDriver session gracefully.

Import a module from a relative path

For this case to import into, first I'd turn these folders into Python packages like so:


Then I would do it like this in

from .dirBar import Bar

If I wanted the namespacing to look like Bar.whatever, or

from . import dirBar

If I wanted the namespacing dirBar.Bar.whatever. This second case is useful if you have more modules under the dirBar package.

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

uuid1() is guaranteed to not produce any collisions (under the assumption you do not create too many of them at the same time). I wouldn't use it if it's important that there's no connection between the uuid and the computer, as the mac address gets used to make it unique across computers.

You can create duplicates by creating more than 214 uuid1 in less than 100ns, but this is not a problem for most use cases.

uuid4() generates, as you said, a random UUID. The chance of a collision is really, really, really small. Small enough, that you shouldn't worry about it. The problem is, that a bad random-number generator makes it more likely to have collisions.

This excellent answer by Bob Aman sums it up nicely. (I recommend reading the whole answer.)

Frankly, in a single application space without malicious actors, the extinction of all life on earth will occur long before you have a collision, even on a version 4 UUID, even if you're generating quite a few UUIDs per second.

Android Studio and cannot resolve symbol

Do sth. modification (just to gradle sync) over app level build.gradle and sync. Again, redo what you changed in build.gradle and sync. It should fix your problem.

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

My mistake, I shouldn't have used a method inside a LINQ query.

Correct code:

using Microsoft.AspNet.Identity;

string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

How to do case insensitive search in Vim

put this command in your vimrc file

set ic 

always do case insensitive search

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

If you are using Facebook SDK, you don't need to bother yourself to enter anything for redirect URI on the app management page of facebook. Just setup a URL scheme for your iOS app. The URL scheme of your app should be a value "fbxxxxxxxxxxx" where xxxxxxxxxxx is your app id as identified on facebook. To setup URL scheme for your iOS app, go to info tab of your app settings and add URL Type.

Is there a download function in jsFiddle?

There is npm-package jsfiddle-downloader.

Difference between Node object and Element object?

A node is the generic name for any type of object in the DOM hierarchy. A node could be one of the built-in DOM elements such as document or document.body, it could be an HTML tag specified in the HTML such as <input> or <p> or it could be a text node that is created by the system to hold a block of text inside another element. So, in a nutshell, a node is any DOM object.

An element is one specific type of node as there are many other types of nodes (text nodes, comment nodes, document nodes, etc...).

The DOM consists of a hierarchy of nodes where each node can have a parent, a list of child nodes and a nextSibling and previousSibling. That structure forms a tree-like hierarchy. The document node has the html node as its child. The html node has its list of child nodes (the head node and the body node). The body node would have its list of child nodes (the top level elements in your HTML page) and so on.

So, a nodeList is simply an array-like list of nodes.

An element is a specific type of node, one that can be directly specified in the HTML with an HTML tag and can have properties like an id or a class. can have children, etc... There are other types of nodes such as comment nodes, text nodes, etc... with different characteristics. Each node has a property .nodeType which reports what type of node it is. You can see the various types of nodes here (diagram from MDN):

enter image description here

You can see an ELEMENT_NODE is one particular type of node where the nodeType property has a value of 1.

So document.getElementById("test") can only return one node and it's guaranteed to be an element (a specific type of node). Because of that it just returns the element rather than a list.

Since document.getElementsByClassName("para") can return more than one object, the designers chose to return a nodeList because that's the data type they created for a list of more than one node. Since these can only be elements (only elements typically have a class name), it's technically a nodeList that only has nodes of type element in it and the designers could have made a differently named collection that was an elementList, but they chose to use just one type of collection whether it had only elements in it or not.

EDIT: HTML5 defines an HTMLCollection which is a list of HTML Elements (not any node, only Elements). A number of properties or methods in HTML5 now return an HTMLCollection. While it is very similar in interface to a nodeList, a distinction is now made in that it only contains Elements, not any type of node.

The distinction between a nodeList and an HTMLCollection has little impact on how you use one (as far as I can tell), but the designers of HTML5 have now made that distinction.

For example, the element.children property returns a live HTMLCollection.

How to find nth occurrence of character in a string?

My solution:

 * Like String.indexOf, but find the n:th occurance of c
 * @param s string to search
 * @param c character to search for
 * @param n n:th character to seach for, starting with 1
 * @return the position (0-based) of the found char, or -1 if failed

public static int nthIndexOf(String s, char c, int n) {
    int i = -1;
    while (n-- > 0) {
        i = s.indexOf(c, i + 1);
        if (i == -1)
    return i;

How to read/process command line arguments?

Pocoo's click is more intuitive, requires less boilerplate, and is at least as powerful as argparse.

The only weakness I've encountered so far is that you can't do much customization to help pages, but that usually isn't a requirement and docopt seems like the clear choice when it is.

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

First, sudo pip install 'package-name' means nothing it will return

sudo: pip: command not found

You get the Permission denied, you shouldn't use pip install as root anyway. You can just install the packages into your own user like mentionned above with

pip install 'package-name' --user

and it will work as you intend. If you need it in any other user just run the same command and you'll be good to go.

Deleting Objects in JavaScript

This work for me, although its not a good practice. It simply delete all the the associated element with which the object belong.

 for (element in homeService) {
          delete homeService[element];

How can I create database tables from XSD files?

XML Schemas describe hierarchial data models and may not map well to a relational data model. Mapping XSD's to database tables is very similar mapping objects to database tables, in fact you could use a framework like Castor that does both, it allows you to take a XML schema and generate classes, database tables, and data access code. I suppose there are now many tools that do the same thing, but there will be a learning curve and the default mappings will most like not be what you want, so you have to spend time customizing whatever tool you use.

XSLT might be the fastest way to generate exactly the code that you want. If it is a small schema hardcoding it might be faster than evaluating and learing a bunch of new technologies.

How to play YouTube video in my Android application?

Google has a YouTube Android Player API that enables you to incorporate video playback functionality into your Android applications. The API itself is very easy to use and works well. For example, here is how to create a new activity to play a video using the API.

Intent intent = YouTubeStandalonePlayer.createVideoIntent(this, "<<YOUTUBE_API_KEY>>", "<<Youtube Video ID>>", 0, true, false);   

See this for more details.

Read next word in java

You can just use Scanner to read word by word, reads the next word

try {
  Scanner s = new Scanner(new File(filename));

  while (s.hasNext()) {
    System.out.println("word:" +;
} catch (IOException e) {
  System.out.println("Error accessing input file!");

how to set mongod --dbpath

Scenario: MongoDB(version v4.0.9).

  1. Set custom folder(with name: myCustomDatabases), where to store databases.
  2. In custom folder(with name: myCustomDatabases), have to create database (with name: newDb).


  1. Create custom folder(with name: myCustomDatabases):

    D:>md myCustomDatabases
  2. Run 'mongod --dbpath' with path to custom folder(with name: myCustomDatabases):

    mongod --dbpath "D:\myCustomDatabases"
  3. From another 'cmd' run 'mongo':


    3.1. Show all databases, stored in custom folder(with name: myCustomDatabases):

    >show dbs
    admin   0.000GB
    config  0.000GB
    local   0.000GB

    3.2. Use database with name newDb:

    > use newDb
    switched to db newDb

    3.3. Show all databases, stored in custom folder(with name: myCustomDatabases):

    >show dbs
    admin   0.000GB
    config  0.000GB
    local   0.000GB

    !!! Noticed, that newDb is NOT in the list !!!

    3.4. Have to create a collection with a document, which will create the database newDb.

    > db.Cats.insert({name: 'Leo'})
    WriteResult({ "nInserted" : 1 })

    The insert({name: 'Leo'}) operation creates: the database newDB and the collection Cats, because they do not exist.

    3.5. Now the new created database newDb will be displayed in the list.

    > show dbs
    admin   0.000GB
    config  0.000GB
    local   0.000GB
    newDb   0.000GB

    3.6. Now in custom folder D:\myCustomDatabases, have database newDb.

Twitter bootstrap progress bar animation on page load

Bootstrap uses CSS3 transitions so progress bars are automatically animated when you set the width of .bar trough javascript / jQuery. ..see?

How to convert wstring into string?

Instead of including locale and all that fancy stuff, if you know for FACT your string is convertible just do this:

#include <iostream>
#include <string>

using namespace std;

int main()
  wstring w(L"bla");
  string result;
  for(char x : w)
    result += x;

  cout << result << '\n';

Live example here

The transaction manager has disabled its support for remote/network transactions

I was getting this issue intermittently, I had followed the instructions here and very similar ones elsewhere. All was configured correctly.

This page: helped me find the problem.

Basically I had duplicate CID's for the MSDTC across both servers. HKEY_CLASSES_ROOT\CID

See: section Ensure that MSDTC is assigned a unique CID value

I am working with virtual servers and our server team likes to use the same image for every server. It's a simple fix and we didn't need a restart. But the DTC service did need setting to Automatic startup and did need to be started after the re-install.

How to change default Anaconda python environment

Load your "base" environment -- as OP's py34 -- when you load your terminal/shell.

If you use Bash, put the line:

conda activate py34

in your .bash_profile (or .bashrc):

$ echo 'conda activate py34' >> ~/.bash_profile

Every time you run a new terminal, conda environment py34 will be loaded.

How to calculate date difference in JavaScript?

var DateDiff = {

    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000));

    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000*7));

    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M+12*d2Y)-(d1M+12*d1Y);

    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();

var dString = "May, 20, 1984";

var d1 = new Date(dString);
var d2 = new Date();

document.write("<br />Number of <b>days</b> since "+dString+": "+DateDiff.inDays(d1, d2));
document.write("<br />Number of <b>weeks</b> since "+dString+": "+DateDiff.inWeeks(d1, d2));
document.write("<br />Number of <b>months</b> since "+dString+": "+DateDiff.inMonths(d1, d2));
document.write("<br />Number of <b>years</b> since "+dString+": "+DateDiff.inYears(d1, d2));

Code sample taken from here.

AngularJS sorting rows by table header

You can use this code without arrows.....i.e by clicking on header it automatically shows ascending and descending order of elements

    <!DOCTYPE html>
<html xmlns="">
    <script src="scripts/angular.min.js"></script>
    <script src="Scripts/Script.js"></script>
        table {
            border-collapse: collapse;
            font-family: Arial;

        td {
            border: 1px solid black;
            padding: 5px;

        th {
            border: 1px solid black;
            padding: 5px;
            text-align: left;
<body ng-app="myModule">
    <div ng-controller="myController">

        <br /><br />
                        <a href="#" ng-click="orderByField='name'; reverseSort = !reverseSort">
                        <a href="#" ng-click="orderByField='dateOfBirth'; reverseSort = !reverseSort">
                            Date Of Birth
                        <a href="#" ng-click="orderByField='gender'; reverseSort = !reverseSort">
                        <a href="#" ng-click="orderByField='salary'; reverseSort = !reverseSort">
                <tr ng-repeat="employee in employees | orderBy:orderByField:reverseSort">
                        {{ }}
                        {{ employee.dateOfBirth | date:"dd/MM/yyyy" }}
                        {{ employee.gender }}
                        {{ employee.salary  }}
        var app = angular
        .module("myModule", [])
        .controller("myController", function ($scope) {

            var employees = [
                    name: "Ben", dateOfBirth: new Date("November 23, 1980"),
                    gender: "Male", salary: 55000
                    name: "Sara", dateOfBirth: new Date("May 05, 1970"),
                    gender: "Female", salary: 68000
                    name: "Mark", dateOfBirth: new Date("August 15, 1974"),
                    gender: "Male", salary: 57000
                    name: "Pam", dateOfBirth: new Date("October 27, 1979"),
                    gender: "Female", salary: 53000
                    name: "Todd", dateOfBirth: new Date("December 30, 1983"),
                    gender: "Male", salary: 60000

            $scope.employees = employees;
            $scope.orderByField = 'name';
            $scope.reverseSort = false;


How to configure for SpringJUnit4ClassRunner?

I was using Maven in eclipse and I did not want to have an additional copy of the properties file in the root folder. You can do the following in eclipse:

  1. Open run dialog (click the little arrow next to the play button and go to run configurations)
  2. Go to the "classpath" tab
  3. Select the "User Entries" and click the "Advanced" button on the right side.
  4. Now select the "Add External folder" radio button.
  5. Select the resources folder

Having Django serve downloadable files

def qrcodesave(request): 
    import urllib2;   
    url ="|0"; 
    opener = urllib2.urlopen(url);  
    content_type = "application/octet-stream"
    response = HttpResponse(, content_type=content_type)
    response["Content-Disposition"]= "attachment; filename=aktel.png"
    return response 

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.

readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;

        function receivedBinary() {
            showResult(fr, "Binary");

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;

<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).

* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.


Right-Click on your project -> Properties -> Deployment Assembly.

On the Left-hand panel Click 'Add' and add the 'Project and External Dependencies'.

'Project and External Dependencies' will have all the spring related jars deployed along with your application

Javascript change color of text and background to input value

document.getElementById("fname").style.borderTopColor = 'red';
document.getElementById("fname").style.borderBottomColor = 'red';

WPF TabItem Header Styling

While searching for a way to round tabs, I found Carlo's answer and it did help but I needed a bit more. Here is what I put together, based on his work. This was done with MS Visual Studio 2015.

The Code:

<Window x:Class="MainWindow"
        Title="Rounded Tabs Example" Height="550" Width="700" WindowStartupLocation="CenterScreen" FontFamily="DokChampa" FontSize="13.333" ResizeMode="CanMinimize" BorderThickness="0">
        <DropShadowEffect Opacity="0.5"/>
    <Grid Background="#FF423C3C">
        <TabControl x:Name="tabControl" TabStripPlacement="Left" Margin="6,10,10,10" BorderThickness="3">
                <Style TargetType="{x:Type TabItem}">
                    <Setter Property="Template">
                            <ControlTemplate TargetType="{x:Type TabItem}">
                                    <Border Name="Border" Background="#FF6E6C67" Margin="2,2,-8,0" BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="10">
                                        <ContentPresenter x:Name="ContentSite" ContentSource="Header" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="2,2,12,2" RecognizesAccessKey="True"/>
                                    <Rectangle Height="100" Width="10" Margin="0,0,-10,0" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Right" StrokeThickness="0" Fill="#FFD4D0C8"/>
                                    <Trigger Property="IsSelected" Value="True">
                                        <Setter Property="FontWeight" Value="Bold" />
                                        <Setter TargetName="ContentSite" Property="Width" Value="30" />
                                        <Setter TargetName="Border" Property="Background" Value="#FFD4D0C8" />
                                    <Trigger Property="IsEnabled" Value="False">
                                        <Setter TargetName="Border" Property="Background" Value="#FF6E6C67" />
                                    <Trigger Property="IsMouseOver" Value="true">
                                        <Setter Property="FontWeight" Value="Bold" />
                    <Setter Property="HeaderTemplate">
                                <ContentPresenter Content="{TemplateBinding Content}">
                                        <RotateTransform Angle="270" />
                    <Setter Property="Background" Value="#FF6E6C67" />
                    <Setter Property="Height" Value="90" />
                    <Setter Property="Margin" Value="0" />
                    <Setter Property="Padding" Value="0" />
                    <Setter Property="FontFamily" Value="DokChampa" />
                    <Setter Property="FontSize" Value="16" />
                    <Setter Property="VerticalAlignment" Value="Top" />
                    <Setter Property="HorizontalAlignment" Value="Right" />
                    <Setter Property="UseLayoutRounding" Value="False" />
                <Style x:Key="tabGrids">
                    <Setter Property="Grid.Background" Value="#FFE5E5E5" />
                    <Setter Property="Grid.Margin" Value="6,10,10,10" />
            <TabItem Header="Planner">
                <Grid Style="{StaticResource tabGrids}"/>
            <TabItem Header="Section 2">
                <Grid Style="{StaticResource tabGrids}"/>
            <TabItem Header="Section III">
                <Grid Style="{StaticResource tabGrids}"/>
            <TabItem Header="Section 04">
                <Grid Style="{StaticResource tabGrids}"/>
            <TabItem Header="Tools">
                <Grid Style="{StaticResource tabGrids}"/>


enter image description here

How to create id with AUTO_INCREMENT on Oracle?

Here is complete solution w.r.t exception/error handling for auto increment, this solution is backward compatible and will work on 11g & 12c, specifically if application is in production.

Please replace 'TABLE_NAME' with your appropriate table name

--checking if table already exisits

--creating table

--checking if sequence already exists

--creating sequence

--granting rights as per required user group

-- creating trigger
    -- auto increment column

    -- You can also put some other required default data as per need of your columns, for example

transform object to array with lodash

You can do

var arr = _.values(obj);

For documentation see here.

How can I format the output of a bash command in neat columns

Found this by searching for "linux output formatted columns".

For your needs, it's like:

awk '{ printf "%-20s %-40s\n", $1, $2}'

Setting font on NSAttributedString on UITextView disregards line spacing

Attributed String Programming Guide:

UIFont *font = [UIFont fontWithName:@"Palatino-Roman" size:14.0];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"strigil" attributes:attrsDictionary];

Update: I tried to use addAttribute: method in my own app, but it seemed to be not working on the iOS 6 Simulator:

NSLog(@"%@", textView.attributedText);

The log seems to show correctly added attributes, but the view on iOS simulator was not display with attributes.

Compare dates with javascript

USe this function for date comparison in javascript:

    function fn_DateCompare(DateA, DateB) {
      var a = new Date(DateA);
      var b = new Date(DateB);

      var msDateA = Date.UTC(a.getFullYear(), a.getMonth()+1, a.getDate());
      var msDateB = Date.UTC(b.getFullYear(), b.getMonth()+1, b.getDate());

      if (parseFloat(msDateA) < parseFloat(msDateB))
        return -1;  // less than
      else if (parseFloat(msDateA) == parseFloat(msDateB))
        return 0;  // equal
      else if (parseFloat(msDateA) > parseFloat(msDateB))
        return 1;  // greater than
        return null;  // error

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

If someone is facing this issue in the hosting services like hostgator or any thing else then you should have to change the value of "localhost" to the relative values which is provided by the hosting provider. In my case it is available in the "phpmyadmin" tab of "cpanel" at the top right corner as "localhost:3302"

Can I have two JavaScript onclick events in one element?


<a href="#" id="btn">click</a>

And the javascript

// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
    if (window.addEventListener) {
        return function(target, type, listener){
            target.addEventListener(type, listener, false);
    else {
        return function(object, sEvent, fpNotify){
            object.attachEvent("on" + sEvent, fpNotify);

// find the element
var el = document.getElementById("btn");

// add the first listener
on(el, "click", function(){

// add the second listener
on(el, "click", function(){

This will alert both 'foo' and 'bar' when clicked.

Getting byte array through input type = file


As noted in comments above, while still on some UA implementations, readAsBinaryString method didn't made its way to the specs and should not be used in production. Instead, use readAsArrayBuffer and loop through it's buffer to get back the binary string :

document.querySelector('input').addEventListener('change', function() {_x000D_
  var reader = new FileReader();_x000D_
  reader.onload = function() {_x000D_
    var arrayBuffer = this.result,_x000D_
      array = new Uint8Array(arrayBuffer),_x000D_
      binaryString = String.fromCharCode.apply(null, array);_x000D_
}, false);
<input type="file" />_x000D_
<div id="result"></div>

For a more robust way to convert your arrayBuffer in binary string, you can refer to this answer.

[old answer] (modified)

Yes, the file API does provide a way to convert your File, in the <input type="file"/> to a binary string, thanks to the FileReader Object and its method readAsBinaryString.
[But don't use it in production !]

document.querySelector('input').addEventListener('change', function(){_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(){_x000D_
        var binaryString = this.result;_x000D_
        document.querySelector('#result').innerHTML = binaryString;_x000D_
  }, false);
<input type="file"/>_x000D_
<div id="result"></div>

If you want an array buffer, then you can use the readAsArrayBuffer() method :

document.querySelector('input').addEventListener('change', function(){_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(){_x000D_
        var arrayBuffer = this.result;_x000D_
        document.querySelector('#result').innerHTML = arrayBuffer + '  '+arrayBuffer.byteLength;_x000D_
  }, false);
<input type="file"/>_x000D_
<div id="result"></div>

Initial size for the ArrayList

If you want a list with a predefined size you can also use:

List<Integer> arr = Arrays.asList(new Integer[10]);

Uploading Images to Server android

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, 1);


public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1)
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = data.getData();

            String filePath = getPath(selectedImage);
            String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);

            try {
                if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
                } else {
                    //NOT IN REQUIRED FORMAT
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block

public String getPath(Uri uri) {
    String[] projection = {MediaColumns.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    column_index = cursor
    imagePath = cursor.getString(column_index);

    return cursor.getString(column_index);


HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("LINK TO SERVER");

Multipart FORM DATA

MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (filePath != null) {
    File file = new File(filePath);
    Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
    Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
    mpEntity.addPart("avatar", new FileBody(file, "application/octet"));


HttpResponse response = httpclient.execute(httppost);

How do I update/upsert a document in Mongoose?

I needed to update/upsert a document into one collection, what I did was to create a new object literal like this:

notificationObject = {
    user_id: user.user_id,
    feed: {
        feed_id: feed.feed_id,
        channel_id: feed.channel_id,
        feed_title: ''

composed from data that I get from somewhere else in my database and then call update on the Model

Notification.update(notificationObject, notificationObject, {upsert: true}, function(err, num, n){
        throw err;
    console.log(num, n);

this is the ouput that I get after running the script for the first time:

1 { updatedExisting: false,
    upserted: 5289267a861b659b6a00c638,
    n: 1,
    connectionId: 11,
    err: null,
    ok: 1 }

And this is the output when I run the script for the second time:

1 { updatedExisting: true, n: 1, connectionId: 18, err: null, ok: 1 }

I'm using mongoose version 3.6.16

GetType used in PowerShell, difference between variables

Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():

PS > $a.GetType().fullname

PS > $b.GetType().fullname

How does one remove a Docker image?

For versions 1.13 and higher:

docker image rm [OPTIONS] IMAGE [IMAGE...]


the [OPTIONS] seem to have no difference.

--force , -f        Force removal of the image
--no-prune          Do not delete untagged parents

From: Introducing Docker 1.13

CLI restructured

In Docker 1.13, we regrouped every command to sit under the logical object it’s interacting with. For example list and start of containers are now subcommands of docker container and history is a subcommand of docker image.

These changes let us clean up the Docker CLI syntax, improve help text and make Docker simpler to use. The old command syntax is still supported, but we encourage everybody to adopt the new syntax.

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

I had the same sittuation , I had many buttongroup insite my item on listview and I was changing some boolean values inside my item like holder.rbVar.setOnclik...

my problem occured because I was calling a method inside getView(); and was saving an object inside sharepreference, so I had same error above

How I solved it; I removed my method inside getView() to notifyDataSetInvalidated() and problem gone

    public void notifyDataSetChanged() {

What's the function like sum() but for multiplication? product()?

There isn't one built in, but it's simple to roll your own, as demonstrated here:

import operator
def prod(factors):
    return reduce(operator.mul, factors, 1)

See answers to this question:

Which Python module is suitable for data manipulation in a list?

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

Another solution is to fix the socket location in the php.ini configuration file like this:


Of course, the symlink works too, so its a matter of preference which one you change.

VHDL - How should I create a clock in a testbench?

My favoured technique:

signal clk : std_logic := '0'; -- make sure you initialise!
clk <= not clk after half_period;

I usually extend this with a finished signal to allow me to stop the clock:

clk <= not clk after half_period when finished /= '1' else '0';

Gotcha alert: Care needs to be taken if you calculate half_period from another constant by dividing by 2. The simulator has a "time resolution" setting, which often defaults to nanoseconds... In which case, 5 ns / 2 comes out to be 2 ns so you end up with a period of 4ns! Set the simulator to picoseconds and all will be well (until you need fractions of a picosecond to represent your clock time anyway!)

What is the most efficient way to store tags in a database?

You can't really talk about slowness based on the data you provided in a question. And I don't think you should even worry too much about performance at this stage of developement. It's called premature optimization.

However, I'd suggest that you'd include Tag_ID column in the Tags table. It's usually a good practice that every table has an ID column.

Proxy with express.js

I used the following setup to direct everything on /rest to my backend server (on port 8080), and all other requests to the frontend server (a webpack server on port 3001). It supports all HTTP-methods, doesn't lose any request meta-info and supports websockets (which I need for hot reloading)

var express  = require('express');
var app      = express();
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
var backend = 'http://localhost:8080',
    frontend = 'http://localhost:3001';

app.all("/rest/*", function(req, res) {
  apiProxy.web(req, res, {target: backend});

app.all("/*", function(req, res) {
    apiProxy.web(req, res, {target: frontend});

var server = require('http').createServer(app);
server.on('upgrade', function (req, socket, head) {, socket, head, {target: frontend});

How to format a duration in java? (e.g format H:MM:SS)

This is a working option.

public static String showDuration(LocalTime otherTime){          
    DateTimeFormatter df = DateTimeFormatter.ISO_LOCAL_TIME;
    LocalTime now =;
    System.out.println("now: " + now);
    System.out.println("otherTime: " + otherTime);
    System.out.println("otherTime: " + otherTime.format(df));

    Duration span = Duration.between(otherTime, now);
    LocalTime fTime = LocalTime.ofNanoOfDay(span.toNanos());
    String output = fTime.format(df);

    return output;

Call the method with

System.out.println(showDuration(LocalTime.of(9, 30, 0, 0)));

Produces something like:

otherTime: 09:30
otherTime: 09:30:00

Python - round up to the nearest ten

round does take negative ndigits parameter!

>>> round(46,-1)

may solve your case.

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

AssemblyInformationalVersion and AssemblyFileVersion are displayed when you view the "Version" information on a file through Windows Explorer by viewing the file properties. These attributes actually get compiled in to a VERSION_INFO resource that is created by the compiler.

AssemblyInformationalVersion is the "Product version" value. AssemblyFileVersion is the "File version" value.

The AssemblyVersion is specific to .NET assemblies and is used by the .NET assembly loader to know which version of an assembly to load/bind at runtime.

Out of these, the only one that is absolutely required by .NET is the AssemblyVersion attribute. Unfortunately it can also cause the most problems when it changes indiscriminately, especially if you are strong naming your assemblies.

Ruby Hash to array of values

hash.collect { |k, v| v }
#returns [["a", "b", "c"], ["b", "c"]] 

Enumerable#collect takes a block, and returns an array of the results of running the block once on every element of the enumerable. So this code just ignores the keys and returns an array of all the values.

The Enumerable module is pretty awesome. Knowing it well can save you lots of time and lots of code.

Eclipse can't find / load main class

.metadata is corrupted.


Warning: Deleting .metadata will delete all your Eclipse configurations, plugins, project setups. Make a backup before you attempt this!

  1. Stop eclipse, delete .metadata in workspace and restart eclipse

  2. Import Project

  3. Run again

ssh script returns 255 error

This error will also occur when using pdsh to hosts which are not contained in your "known_hosts" file.

I was able to correct this by SSH'ing into each host manually and accepting the question "Do you want to add this to known hosts".

Java Error opening registry key

I have Windows 7. I got the same problem after installing: PyCharm. I wasn't satisfied with PyCharm, so I decided to use Eclipse instead. This is when I discovered that things went wrong with my JDK. I used to have Java.9.x. So I decided to uninstall it and get the newer version (at my time it was Java.11.x. The same problem persisted. I followed most of the steps mentioned above in the post like: - Removing all java*.exe files, - removing Java related entries from the registry. - Cleaning-up all unnecessary Java folders. However nothing helped. I still had something in the system referring to a broken Java pathname.

What really brought remedy is the following: - Uninstalled what ever version of JDK I had at the moment. - Re-Installed the last JDK version I had before the problem took place - Properly uninstall that version. - Install whatever latest version of SDK. ..

That's it .. at this point everything returned to normal ... Except that Java.11.xx did not fix the system path automatically, I had to do it manually.

LDAP root query syntax to search more than one specific OU

You can!!! In short use this as the connection string:


together with your search filter, e.g.


That will search in the so called Global Catalog, that had been available out-of-the-box in our environment.

Instead of the known/common other versions (or combinations thereof) that did NOT work in our environment with multiple OUs:

ldap://<host>:389/DC=<my>,DC=<domain>  (standard port)
ldap://<host>/(|(OU=<someOU1>)(OU=<someOU2>)),DC=<my>,DC=<domain> (search filters here shouldn't work at all by definition)

(I am a developer, not an AD/LDAP guru:) Damn I had been searching for this solution everywhere for almost 2 days and almost gave up, getting used to the thought I might have to implement this obviously very common scenario by hand (with Jasperserver/Spring security(/Tomcat)). (So this shall be a reminder if somebody else or me should have this problem again in the future :O) )

Here some other related threads I found during my research that had been mostly of little help:

And here I will provide our anonymized Tomcat LDAP config in case it may be helpful (/var/lib/tomcat7/webapps/jasperserver/WEB-INF/applicationContext-externalAUTH-LDAP.xml):

<beans xmlns=""

<!-- ############ LDAP authentication ############ - Sample configuration 
    of external authentication via an external LDAP server. -->

<bean id="proxyAuthenticationProcessingFilter"
    <property name="authenticationManager">
        <ref local="ldapAuthenticationManager" />
    <property name="externalDataSynchronizer">
        <ref local="externalDataSynchronizer" />

    <property name="sessionRegistry">
        <ref bean="sessionRegistry" />

    <property name="internalAuthenticationFailureUrl" value="/login.html?error=1" />
    <property name="defaultTargetUrl" value="/loginsuccess.html" />
    <property name="invalidateSessionOnSuccessfulAuthentication"
        value="true" />
    <property name="migrateInvalidatedSessionAttributes" value="true" />

<bean id="proxyAuthenticationSoapProcessingFilter"
    <property name="authenticationManager" ref="ldapAuthenticationManager" />
    <property name="externalDataSynchronizer" ref="externalDataSynchronizer" />

    <property name="invalidateSessionOnSuccessfulAuthentication"
        value="true" />
    <property name="migrateInvalidatedSessionAttributes" value="true" />
    <property name="filterProcessesUrl" value="/services" />

<bean id="proxyRequestParameterAuthenticationFilter"
    <property name="authenticationManager">
        <ref local="ldapAuthenticationManager" />
    <property name="externalDataSynchronizer" ref="externalDataSynchronizer" />

    <property name="authenticationFailureUrl">
    <property name="excludeUrls">

<bean id="proxyBasicProcessingFilter"
    <property name="authenticationManager" ref="ldapAuthenticationManager" />
    <property name="externalDataSynchronizer" ref="externalDataSynchronizer" />

    <property name="authenticationEntryPoint">
        <ref local="basicProcessingFilterEntryPoint" />

<bean id="proxyAuthenticationRestProcessingFilter"
    <property name="authenticationManager">
        <ref local="ldapAuthenticationManager" />
    <property name="externalDataSynchronizer">
        <ref local="externalDataSynchronizer" />

    <property name="filterProcessesUrl" value="/rest/login" />
    <property name="invalidateSessionOnSuccessfulAuthentication"
        value="true" />
    <property name="migrateInvalidatedSessionAttributes" value="true" />

<bean id="ldapAuthenticationManager" class="">
    <property name="providers">
            <ref local="ldapAuthenticationProvider" />
            <ref bean="${bean.daoAuthenticationProvider}" />
            <!--anonymousAuthenticationProvider only needed if filterInvocationInterceptor.alwaysReauthenticate 
                is set to true <ref bean="anonymousAuthenticationProvider"/> -->

<bean id="ldapAuthenticationProvider"
                <ref local="ldapContextSource" />
            <property name="userSearch" ref="userSearch" />
            <constructor-arg index="0">
                <ref local="ldapContextSource" />
            <constructor-arg index="1">

            <property name="groupRoleAttribute" value="cn" />
            <property name="convertToUpperCase" value="true" />
            <property name="rolePrefix" value="ROLE_" />
            <property name="groupSearchFilter"
                value="(&amp;(member={0})(&amp;(objectCategory=Group)(objectclass=group)(cn=my-nested-group-name)))" />
            <property name="searchSubtree" value="true" />
            <!-- Can setup additional external default roles here <property name="defaultRole" 
                value="LDAP"/> -->

<bean id="userSearch"
    <constructor-arg index="0">
    <constructor-arg index="1">
    <constructor-arg index="2">
        <ref local="ldapContextSource" />
    <property name="searchSubtree">

<bean id="ldapContextSource"
    <constructor-arg value="ldap://myhost:3268/DC=dc3,DC=dc2,DC=dc1?cn" />
    <!-- manager user name and password (may not be needed) -->
    <property name="userDn" value="CN=someuser,OU=ou4,OU=1,DC=dc3,DC=dc2,DC=dc1" />
    <property name="password" value="somepass" />
    <!--End Changes -->
<!-- ############ LDAP authentication ############ -->

<!-- ############ JRS Synchronizer ############ -->
<bean id="externalDataSynchronizer"
    <property name="externalUserProcessors">
            <ref local="externalUserSetupProcessor" />
            <!-- Example processor for creating user folder -->
            <!--<ref local="externalUserFolderProcessor"/> -->

<bean id="abstractExternalProcessor"
    <property name="repositoryService" ref="${bean.repositoryService}" />
    <property name="userAuthorityService" ref="${bean.userAuthorityService}" />
    <property name="tenantService" ref="${bean.tenantService}" />
    <property name="profileAttributeService" ref="profileAttributeService" />
    <property name="objectPermissionService" ref="objectPermissionService" />

<bean id="externalUserSetupProcessor"
    <property name="userAuthorityService">
        <ref bean="${bean.internalUserAuthorityService}" />
    <property name="defaultInternalRoles">

    <property name="organizationRoleMap">
            <!-- Example of mapping customer roles to JRS roles -->
                <!-- JRS role that the <key> external role is mapped to -->

<!--bean id="externalUserFolderProcessor" class="" 
    parent="abstractExternalProcessor"> <property name="repositoryService" ref="${bean.unsecureRepositoryService}"/> 
    </bean -->

<!-- ############ JRS Synchronizer ############ -->

OSError: [Errno 8] Exec format error

OSError: [Errno 8] Exec format error can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:

>>> with open('a','w') as f: f.write('exit 0') # create the script
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable                       
>>> os.execl('./a', './a')     # execute it                                            
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/", line 312, in execl
    execv(file, args)
OSError: [Errno 8] Exec format error

To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh at the top of your script:

>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
>>> os.execl('./a', './a')

It executes exit 0 without any errors.

On POSIX systems, shell parses the command line i.e., your script won't see spaces around = e.g., if script is:

#!/usr/bin/env python
import sys

then running it in the shell:

$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST


['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']

Note: no spaces around '='. I've added quotes around <hostname> to escape the redirection metacharacters <>.

To emulate the shell command in Python, run:

from subprocess import check_call

cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']

Note: no shell=True. And you don't need to escape <> because no shell is run.

"Exec format error" might indicate that your script has invalid format, run:

$ file /usr/local/bin/script

to find out what it is. Compare the architecture with the output of:

$ uname -m

Assign a login to a user created without login (SQL Server)

You have an orphaned user and this can't be remapped with ALTER USER (yet) becauses there is no login to map to. So, you need run CREATE LOGIN first.

If the database level user is

  • a Windows Login, the mapping will be fixed automatcially via the AD SID
  • a SQL Login, use "sid" from sys.database_principals for the SID option for the login


Edit, after comments and updates

The sid from sys.database_principals is for a Windows login.

So trying to create and re-map to a SQL Login will fail

Run this to get the Windows login

SELECT SUSER_SNAME(0x0105000000000009030000001139F53436663A4CA5B9D5D067A02390)

Mysql 1050 Error "Table already exists" when in fact, it does not

I've been fighting with this all day: I have a Perl script that builds a set of tables by first doing a DROP IF EXISTS ... on them and then CREATEing them. The DROP succeeded, but on CREATE I got this error message: table already exists

I finally got to the bottom of it: The new version of MySQL that I'm using has a default engine of InnoDB ("show engine \G;") I changed it in the my.cnf file to default to MyISAM, re-started MySQL, and now I no longer get the "table already exists" error.

How to view the Folder and Files in GAC?

I'm a day late and a dollar short on this one. If you want to view the folder structure of the GAC in Windows Explorer, you can do this by using the registry:

  1. Launch regedit.
  2. Navigate to HKLM\Software\Microsoft\Fusion
  3. Add a DWORD called DisableCacheViewer and set the value to 1.

For a temporary view, you can substitute a drive for the folder path, which strips away the special directory properties.

  1. Launch a Command Prompt at your account's privilege level.
  2. Type SUBST Z: C:\Windows\assembly
    • Z can be any free drive letter.
  3. Open My Computer and look in the new substitute directory.
  4. To remove the virtual drive from Command Prompt, type SUBST Z: /D

As for why you'd want to do something like this, I've used this trick to compare GAC'd DLLs between different machines to make sure they're truly the same.

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

I have python 2.7.13 and 3.6.2 both installed. Install Anaconda for python 3 first and then you can use conda syntax to get 2.7. My install used: conda create -n py27 python=2.7.13 anaconda

Can we create an instance of an interface in Java?

Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here:

interface ProgrammerInterview {
    public void read();

class Website {
    ProgrammerInterview p = new ProgrammerInterview() {
        public void read() {
            System.out.println("interface ProgrammerInterview class implementer");

This works fine. Was taken from this page:

Is there Selected Tab Changed Event in the standard WPF Tab Control

If you just want to have an event when a tab is selected, this is the correct way:

    <TabItem Selector.Selected="OnTabSelected" />
    <TabItem Selector.Selected="OnTabSelected" />
    <TabItem Selector.Selected="OnTabSelected" />
    <!-- You can also catch the unselected event -->
    <TabItem Selector.Unselected="OnTabUnSelected" />

And in your code

    private void OnTabSelected(object sender, RoutedEventArgs e)
        var tab = sender as TabItem;
        if (tab != null)
            // this tab is selected!

How do I resolve a HTTP 414 "Request URI too long" error?

I have a simple workaround.

Suppose your URI has a string stringdata that is too long. You can simply break it into a number of parts depending on the limits of your server. Then submit the first one, in my case to write a file. Then submit the next ones to append to previously added data.

Cell color changing in Excel using C#

Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW, FIRST_COL, and LAST_COL, and that _xlSheet is the name of the ExcelSheet (using Microsoft.Interop.Excel)

First, define the range:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

Then, set the background color of that range:

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

Finally, set the font color:

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

And here's the code combined:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

Well! I observer Heroku is famous in budding and newly born developers while AWS has advanced developer persona. DigitalOcean is also a major player in this ground. Cloudways has made it much easy to create Lamp stack in a click on DigitalOcean and AWS. Having all services and packages updates in a click is far better than doing all thing manually.

You can check out completely here:

How to fit in an image inside span tag?

Try this.

<span style="padding-right:3px; padding-top: 3px; display:inline-block;">

<img class="manImg" src="images/ico_mandatory.gif"></img>


webpack is not recognized as a internal or external command,operable program or batch file

If you create a boilerplate folder for your JS projects so that you can use JS Modules, webpack and Babel are great tools.

Don't install webpack globally and after installing the most recent versions of both, your package.json file will be loaded up and ready to copy for future projects.

Make sure to delete the node_modules folder to decrease file size in your boilerplate folder and then to reinstall node_modules use npm install.

I forgot to run npm install and kept getting this error when trying to run my webpack dev-server until I realized I needed to run npm install to install node_modules and then it worked.

How to assign the output of a command to a Makefile variable

With GNU Make, you can use shell and eval to store, run, and assign output from arbitrary command line invocations. The difference between the example below and those which use := is the := assignment happens once (when it is encountered) and for all. Recursively expanded variables set with = are a bit more "lazy"; references to other variables remain until the variable itself is referenced, and the subsequent recursive expansion takes place each time the variable is referenced, which is desirable for making "consistent, callable, snippets". See the manual on setting variables for more info.

# Generate a random number.
# This is not run initially.
GENERATE_ID = $(shell od -vAn -N2 -tu2 < /dev/urandom)

# Generate a random number, and assign it to MY_ID
# This is not run initially.

# You can use .PHONY to tell make that we aren't building a target output file
.PHONY: mytarget
# This is empty when we begin
    @echo $(MY_ID)
# This recursively expands SET_ID, which calls the shell command and sets MY_ID
# This will now be a random number
    @echo $(MY_ID)
# Recursively expand SET_ID again, which calls the shell command (again) and sets MY_ID (again)
# This will now be a different random number
    @echo $(MY_ID)

How to safely open/close files in python 2.4


When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.

Hence use close() elegantly with try/finally:

f = open('file.txt', 'r')

    # do stuff with f

This ensures that even if # do stuff with f raises an exception, f will still be closed properly.

Note that open should appear outside of the try. If open itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open raises an exception its result is not assigned to f and it is an error to call f.close().

How correctly produce JSON by RESTful web service?

Use this annotation

@RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})

Getting value from table cell in JavaScript...not jQuery

function GetCellValues() {
    var table = document.getElementById('mytable');
    for (var r = 0, n = table.rows.length; r < n; r++) {
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {

Get PostGIS version

Other way to get the minor version is:

SELECT extversion
FROM pg_catalog.pg_extension
WHERE extname='postgis'

How do I give ASP.NET permission to write to a folder in Windows 7?

Giving write permissions to all IIS_USRS group is a bad idea from the security point of view. You dont need to do that and you can go with giving permissions only to system user running the application pool.

If you are using II7 (and I guess you do) do the following.

  1. Open IIS7
  2. Select Website for which you need to modify permissions
  3. Go to Basic Settings and see which application pool you're using.
  4. Go to Application pools and find application pool from #3
  5. Find system account used for running this application pool (Identity column)
  6. Navigate to your storage folder in IIS, select it and click on Edit Permissions (under Actions sub menu on the right)
  7. Open security tab and add needed permissions only for user you identified in #3

Note #1: if you see ApplicationPoolIdentity in #3 you need to reference this system user like this IIS AppPool{application_pool_name} . For example IIS AppPool\DefaultAppPool

Note #2: when adding this user make sure to set correct locations in the Select Users or Groups dialog. This needs to be set to local machine because this is local account.

How to change workspace and build record Root Directory on Jenkins?

I would suggest editing the /etc/default/jenkins

vi /etc/default/jenkins

And changing the $JENKINS_HOME variable (around line 23) to


Then restart the Jenkins with usual

/etc/init.d/jenkins start


Node.js create folder or use existing

You can also use fs-extra, which provide a lot frequently used file operations.

Sample Code:

var fs = require('fs-extra')

fs.mkdirs('/tmp/some/long/path/that/prob/doesnt/exist', function (err) {
  if (err) return console.error(err)


docs here:

Setting timezone to UTC (0) in PHP

You can always check this maintained list to timezones

TSQL: How to convert local time to UTC? (SQL Server 2008)


Returns (for example):


Not 100% positive this will always work.

How to use source: function()... and AJAX in JQuery UI autocomplete

  source: function(request, response) {
      url: "api/listBasicsubject",
      dataType: "json",
      type: "post",
      data: {
        search: request.term
      success: function(data) {

        if (!data.length) {
          var result = [{
            label: 'Subject not found',
            value: response.term
        } else {
          response($.map(, function(item) {
            return {
              label: item.subject_name,
              value: item.subject_id
  change: function(event, ui) {
    if (ui.item == null) {

  minLength: 0,
  classes: {
    "ui-autocomplete": "auto_compl-cat"

  focus: function(event, ui) {
    // $("#subject_name").val(ui.item.label);



  select: function(event, ui) {
    if (ui.item.label == "Subject not found") {

      return false;
    //console.log( "Selected: " + ui.item.label + " aka " + ui.item.value);
    return false;

Selenium Webdriver: Entering text into text field

It might be the JavaScript check for some valid condition.
Two things you can perform a/c to your requirements:

  1. either check for the valid string-input in the text-box.
  2. or set a loop against that text box to enter the value until you post the form/request.
String barcode="0000000047166";

WebElement strLocator = driver.findElement(By.xpath("//*[@id='div-barcode']"));

Javascript Image Resize

Try this..

<script type="text/javascript">
function splitString()
var myDimen=document.getElementById("dimen").value;
var splitDimen = myDimen.split("*");

<h2>Norwegian Mountain Trip</h2>
<img border="0" id="myImage" src="..." alt="Pulpit rock" width="304" height="228" /><br>
<input type="text" id="dimen" name="dimension" />
<input type="submit" value="Submit" Onclick ="splitString()"/>


In the text box give the dimension as ur wish, in the format 50*60. Click submit. You will get the resized image. Give your image path in place of dots in the image tag.

Validate date in dd/mm/yyyy format using JQuery Validate

This validates dd/mm/yyy dates. Edit your jquery.validate.js and add these.

Reference(Regex): Regex to validate date format dd/mm/yyyy

dateBR: function( value, element ) {
    return this.optional(element) || /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/.test(value);

messages: {
    dateBR: "Invalid date."

classRuleSettings: {
    dateBR: {dateBR: true}


$( "#myForm" ).validate({
    rules: {
        field: {
            dateBR: true

javascript how to create a validation error message without using alert


<script language="javascript">
        var flag=0;
        function username()
                document.getElementById("error0").innerHTML="Enter UserID";
        function password()
                document.getElementById("error1").innerHTML="Enter password";   

        function check(form)
                return false;
                return true;



<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">

                    <div id="error0"></div>
                    <input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
                    <div id="error1"></div>
                    <input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">

                    <button type="submit" class="btn">Sign in</button>

How to add a WiX custom action that happens only on uninstall (via MSI)?

The biggest problem with a batch script is handling rollback when the user clicks cancel (or something goes wrong during your install). The correct way to handle this scenario is to create a CustomAction that adds temporary rows to the RemoveFiles table. That way the Windows Installer handles the rollback cases for you. It is insanely simpler when you see the solution.

Anyway, to have an action only execute during uninstall add a Condition element with:


the ~= says compare case insensitive (even though I think ALL is always uppercaesd). See the MSI SDK documentation about Conditions Syntax for more information.

PS: There has never been a case where I sat down and thought, "Oh, batch file would be a good solution in an installation package." Actually, finding an installation package that has a batch file in it would only encourage me to return the product for a refund.

node and Error: EMFILE, too many open files

This will probably fix your problem if you're struggling to deploy a React solution that was created with the Visual Studio template (and has a web.config). In Azure Release Pipelines, when selecting the template, use:

Azure App Service deployment

Instead of:

Deploy a Node.js app to Azure App Service

It worked for me!

Using Java with Microsoft Visual Studio 2012

Using Visual Studio IDE for porting Java to C#:

Currently I am using Visual Studio IDE environment for porting codes from Java to C#. Why? Java has a huge libraries and C# enables the access to the UWP ecosystem.

For supporting editing and debugging as well as examining Java Bytecode (disassembly), you could try:

For supporting Android (Java/C++) development, you could try:

What is the difference between parseInt(string) and Number(string) in JavaScript?

Addendum to @sjngm's answer:

They both also ignore whitespace:

var foo = " 3 "; console.log(parseInt(foo)); // 3 console.log(Number(foo)); // 3

It is not exactly correct. As sjngm wrote parseInt parses string to first number. It is true. But the problem is when you want to parse number separated with whitespace ie. "12 345". In that case
parseInt("12 345") will return 12 instead of 12345. So to avoid that situation you must trim whitespaces before parsing to number. My solution would be:

     var number=parseInt("12 345".replace(/\s+/g, ''),10);

Notice one extra thing I used in parseInt() function. parseInt("string",10) will set the number to decimal format. If you would parse string like "08" you would get 0 because 8 is not a octal number.Explanation is here

SyntaxError: Unexpected Identifier in Chrome's Javascript console

Write it as below

<script language="javascript">
var visitorName = 'Chuck';
var myOldString = 'Hello username. I hope you enjoy your stay username.';

var myNewString = myOldString.replace('username', visitorName);

document.write('Old String = ' + myOldString);
document.write('<br/>New string = ' + myNewString);

How do I profile memory usage in Python?

This one has been answered already here: Python memory profiler

Basically you do something like that (cited from Guppy-PE):

>>> from guppy import hpy; h=hpy()
>>> h.heap()
Partition of a set of 48477 objects. Total size = 3265516 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0  25773  53  1612820  49   1612820  49 str
     1  11699  24   483960  15   2096780  64 tuple
     2    174   0   241584   7   2338364  72 dict of module
     3   3478   7   222592   7   2560956  78 types.CodeType
     4   3296   7   184576   6   2745532  84 function
     5    401   1   175112   5   2920644  89 dict of class
     6    108   0    81888   3   3002532  92 dict (no owner)
     7    114   0    79632   2   3082164  94 dict of type
     8    117   0    51336   2   3133500  96 type
     9    667   1    24012   1   3157512  97 __builtin__.wrapper_descriptor
<76 more rows. Type e.g. '_.more' to view.>
>>> h.iso(1,[],{})
Partition of a set of 3 objects. Total size = 176 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0      1  33      136  77       136  77 dict (no owner)
     1      1  33       28  16       164  93 list
     2      1  33       12   7       176 100 int
>>> x=[]
>>> h.iso(x).sp
 0: h.Root.i0_modules['__main__'].__dict__['x']

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

changing implementation '' to implementation '' worked for me

I am using Intellij 2019 CE, with Kotlin