Programs & Examples On #Rdl

Report Definition Language (RDL) is a standard proposed by Microsoft for defining reports.

When to use RDLC over RDL reports?

From my experience, if you need high performance (this does depend slightly on your client specs) on large reports, go with rdlc. Additionally, rdlc reports give you a very full range of control over your data, you may be able to save yourself wasted database trips, etc. by using client side reports. On the project I'm currently working on, a critical report requires about 2 minutes to render on the server side, and pretty much takes out whichever reporting server it hits for that time. Switching it to client side rendering, we see performance much closer to 20-40 seconds with no load on the report server and less bandwidth used because only the datasets are being downloaded.

Your mileage may vary, and I find rdlc's add development and maintenance complexity, especially when your report has been designed as a server side report.

Open new Terminal Tab from command line (Mac OS X)

Here's how it's done by bash_it:

function tab() {
  osascript 2>/dev/null <<EOF
    tell application "System Events"
      tell process "Terminal" to keystroke "t" using command down
    end
    tell application "Terminal"
      activate
      do script with command "cd \"$PWD\"; $*" in window 1
    end tell
EOF
}

After adding this to your .bash_profile, you'd use the tab command to open the current working directory in a new tab.

See: https://github.com/revans/bash-it/blob/master/plugins/available/osx.plugin.bash#L3

LINQ Contains Case Insensitive

IndexOf works best in this case

return this
   .ObjectContext
   .FACILITY_ITEM
   .Where(fi => fi.DESCRIPTION.IndexOf(description, StringComparison.OrdinalIgnoreCase)>=0);

How do I jump out of a foreach loop in C#?

foreach(string s in sList)
{
    if(s.equals("ok"))
    {
             return true;
    }
}
return false;

How do I change the figure size for a seaborn plot?

Note that if you are trying to pass to a "figure level" method in seaborn (for example lmplot, catplot / factorplot, jointplot) you can and should specify this within the arguments using height and aspect.

sns.catplot(data=df, x='xvar', y='yvar', 
    hue='hue_bar', height=8.27, aspect=11.7/8.27)

See https://github.com/mwaskom/seaborn/issues/488 and Plotting with seaborn using the matplotlib object-oriented interface for more details on the fact that figure level methods do not obey axes specifications.

html 5 audio tag width

You can use html and be a boss with simple things :

<embed src="music.mp3" width="3000" height="200" controls>

Install Node.js on Ubuntu

Follow the instructions given here at NodeSource which is dedicated to creating a sustainable ecosystem for Node.js.

For Node.js >= 4.X

# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
sudo apt-get install -y nodejs

# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_4.x | bash -
apt-get install -y nodejs

How do I write a RGB color value in JavaScript?

I am showing with an example of adding random color. You can write this way

var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
var col = "rgb(" + r + "," + g + "," + b + ")";
parent.childNodes[1].style.color = col;

The property is expected as a string

Best practice: PHP Magic Methods __set and __get

I have been exactly in your case in the past. And I went for magic methods.

This was a mistake, the last part of your question says it all :

  • this is slower (than getters/setters)
  • there is no auto-completion (and this is a major problem actually), and type management by the IDE for refactoring and code-browsing (under Zend Studio/PhpStorm this can be handled with the @property phpdoc annotation but that requires to maintain them: quite a pain)
  • the documentation (phpdoc) doesn't match how your code is supposed to be used, and looking at your class doesn't bring much answers as well. This is confusing.
  • added after edit: having getters for properties is more consistent with "real" methods where getXXX() is not only returning a private property but doing real logic. You have the same naming. For example you have $user->getName() (returns private property) and $user->getToken($key) (computed). The day your getter gets more than a getter and needs to do some logic, everything is still consistent.

Finally, and this is the biggest problem IMO : this is magic. And magic is very very bad, because you have to know how the magic works to use it properly. That's a problem I've met in a team: everybody has to understand the magic, not just you.

Getters and setters are a pain to write (I hate them) but they are worth it.

How to read user input into a variable in Bash?

Try this

#/bin/bash

read -p "Enter a word: " word
echo "You entered $word"

INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

I encountered the same problem with a nexus 5 Android Lollipop 5.0.1:

Installation error: INSTALL_FAILED_DUPLICATE_PERMISSION perm=com.android.** pkg=com.android.**

And in my case I couldn't fix this problem uninstalling the app because it was an android app, but I had to change my app custom permissions name in manifest because they were the same as an android app, which I could not uninstall or do any change.

Hope this helps somebody!

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

When I used --allow-unrelated-histories, this command generated too many conflicts. There were conflicts in files which I didn't even work on. To get over the error " Refusing to merge unrelated histories", I used following rebase command:

git pull --rebase=preserve --allow-unrelated-histories

After this commit the uncommitted changes with a commit message. Finally, run the following command:

git rebase --continue

After this, my working copy was up-to-date with the remote copy and I was able to push my changes as before. No more unrelated histories error while pulling.

How to reenable event.preventDefault?

You can re-activate the actions by adding

this.delegateEvents();  // Re-activates the events for all the buttons

If you add it to the render function of a backbone js view, then you can use event.preventDefault() as required.

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

So far, the accepted answer has worked best for me. However, my concern has always been that there is a likely scenario where I might refactor the notebooks directory into subdirectories, requiring to change the module_path in every notebook. I decided to add a python file within each notebook directory to import the required modules.

Thus, having the following project structure:

project
|__notebooks
   |__explore
      |__ notebook1.ipynb
      |__ notebook2.ipynb
      |__ project_path.py
   |__ explain
       |__notebook1.ipynb
       |__project_path.py
|__lib
   |__ __init__.py
   |__ module.py

I added the file project_path.py in each notebook subdirectory (notebooks/explore and notebooks/explain). This file contains the code for relative imports (from @metakermit):

import sys
import os

module_path = os.path.abspath(os.path.join(os.pardir, os.pardir))
if module_path not in sys.path:
    sys.path.append(module_path)

This way, I just need to do relative imports within the project_path.py file, and not in the notebooks. The notebooks files would then just need to import project_path before importing lib. For example in 0.0-notebook.ipynb:

import project_path
import lib

The caveat here is that reversing the imports would not work. THIS DOES NOT WORK:

import lib
import project_path

Thus care must be taken during imports.

Determine installed PowerShell version

$host.version is just plain wrong/unreliable. This gives you the version of the hosting executable (powershell.exe, powergui.exe, powershell_ise.exe, powershellplus.exe etc) and not the version of the engine itself.

The engine version is contained in $psversiontable.psversion. For PowerShell 1.0, this variable does not exist, so obviously if this variable is not available it is entirely safe to assume the engine is 1.0, obviously.

Confirm deletion using Bootstrap 3 modal box

Create modal dialog in HTML with id="confirmation" and use function showConfirmation.

Also remember you should to unbind (modal.unbind()) cancel and success buttons after hide modal dialog. If you do not make this you will get double binding. For example: if you open dialog once and press 'Cancel' and then open dialog in second time and press 'Ok' you will get 2 executions of success callback.

showConfirmation = function(title, message, success, cancel) {
    title = title ? title : 'Are you sure?';
    var modal = $("#confirmation");
    modal.find(".modal-title").html(title).end()
        .find(".modal-body").html(message).end()
        .modal({ backdrop: 'static', keyboard: false })
        .on('hidden.bs.modal', function () {
            modal.unbind();
        });
    if (success) {
        modal.one('click', '.modal-footer .btn-primary', success);
    }
    if (cancel) {
        modal.one('click', '.modal-header .close, .modal-footer .btn-default', cancel);
    }
};

// bind confirmation dialog on delete buttons
$(document).on("click", ".delete-event, .delete-all-event", function(event){
    event.preventDefault();
    var self = $(this);
    var url = $(this).data('url');
    var success = function(){
        alert('window.location.href=url');
    }
    var cancel = function(){
        alert('Cancel');
    };
    if (self.data('confirmation')) {
        var title = self.data('confirmation-title') ? self.data('confirmation-title') : undefined;
        var message = self.data('confirmation');
        showConfirmation(title, message, success, cancel);
    } else {
        success();
    }
});

https://jsfiddle.net/yiiBoy/hne9sp6g/

ModuleNotFoundError: No module named 'sklearn'

I did the following:

import sys
!{sys.executable} -m pip install sklearn

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Replacing Spaces with Underscores

This is part of my code which makes spaces into underscores for naming my files:

$file = basename($_FILES['upload']['name']);
$file = str_replace(' ','_',$file);

Integrity constraint violation: 1452 Cannot add or update a child row:

I hope my decision will help. I had a similar error in Laravel. I added a foreign key to the wrong table.
Wrong code:

Schema::create('comments', function (Blueprint $table) {
$table->unsignedBigInteger('post_id')->index()->nullable();
...
$table->foreign('post_id')->references('id')->on('comments')->onDelete('cascade');
    });


Schema::create('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    ...
    });

Please note to the function on('comments') above. Correct code

 $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

Named colors in matplotlib

In addition to BoshWash's answer, here is the picture generated by his code:

Named colors

What is the difference between a token and a lexeme?

Token: Token is a sequence of characters that can be treated as a single logical entity. Typical tokens are,
1) Identifiers
2) keywords
3) operators
4) special symbols
5)constants

Pattern: A set of strings in the input for which the same token is produced as output. This set of strings is described by a rule called a pattern associated with the token.
Lexeme: A lexeme is a sequence of characters in the source program that is matched by the pattern for a token.

Min and max value of input in angular4 application

[I assume the reader has basic knowledge of Angular2+ and Forms]

It is easy to show a numerical input and put the limits, but you have to also take care of things may happen out of your predictions.

  1. Implement the tag in your 'html':
<input type="number" [min]="0.00" [max]="100.00" [step]="0.01" formControlName="rateFC">
  1. But as Adrien said, still user can enter manually a wrong number. You can validate input by Validators easily. In your '.ts':
import { FormGroup, FormControl, Validators } from '@angular/forms';

//many other things...

this.myFG = new FormGroup({
   //other form controls...,
   rateFC  : new FormControl(0, [Validators.min(0), Validators.max(100)])
});
  1. Up to now everything is ok, but it is better to let the user know the input is wrong, then draw a red line around the invalid input element by adding to your style:
.form-control.ng-touched.ng-invalid{
    border:2px solid red;
}
  1. And to make it perfect, prevent the user to submit the wrong data.
<button type="submit" [disabled]="!myFG.valid">Submit</button>

Convert a Unix timestamp to time in JavaScript

UNIX timestamp is number of seconds since 00:00:00 UTC on January 1, 1970 (according to Wikipedia).

Argument of Date object in Javascript is number of miliseconds since 00:00:00 UTC on January 1, 1970 (according to W3Schools Javascript documentation).

See code below for example:

    function tm(unix_tm) {
        var dt = new Date(unix_tm*1000);
        document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');

    }

tm(60);
tm(86400);

gives:

1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)

XSL substring and indexOf

I wrote my own index-of function, inspired by strpos() in PHP.

<xsl:function name="fn:strpos">
    <xsl:param name="haystack"/>
    <xsl:param name="needle"/>
    <xsl:value-of select="fn:_strpos($haystack, $needle, 1, string-length($haystack) - string-length($needle))"/>
</xsl:function>

<xsl:function name="fn:_strpos">
    <xsl:param name="haystack"/>
    <xsl:param name="needle"/>
    <xsl:param name="pos"/>
    <xsl:param name="count"/>
    <xsl:choose>
        <xsl:when test="$count &lt; 0">
            <!-- Not found. Most common is to return -1 here (or maybe 0 in XSL?). -->
            <!-- But this way, the result can be used with substring() without checking. -->
            <xsl:value-of select="string-length($haystack) + 1"/>
        </xsl:when>
        <xsl:when test="starts-with(substring($haystack, $pos), $needle)">
            <xsl:value-of select="$pos"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="fn:_strpos($haystack, $needle, $pos + 1, $count - 1)"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:function>

Angular 4 Pipe Filter

The transform method signature changed somewhere in an RC of Angular 2. Try something more like this:

export class FilterPipe implements PipeTransform {
    transform(items: any[], filterBy: string): any {
        return items.filter(item => item.id.indexOf(filterBy) !== -1);
    }
}

And if you want to handle nulls and make the filter case insensitive, you may want to do something more like the one I have here:

export class ProductFilterPipe implements PipeTransform {

    transform(value: IProduct[], filterBy: string): IProduct[] {
        filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
        return filterBy ? value.filter((product: IProduct) =>
            product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
    }
}

And NOTE: Sorting and filtering in pipes is a big issue with performance and they are NOT recommended. See the docs here for more info: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

PHP Configuration: It is not safe to rely on the system's timezone settings

Check for syntax errors in the php.ini file, specially before the Date paramaters, that prevent the file from being parsed correctly.

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

$mysql -u root --host=127.0.0.1 -p

mysql>use mysql

mysql>GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'redhat@123';

mysql>FLUSH PRIVILEGES;

mysql> SELECT host FROM mysql.user WHERE User = 'root';

How to write a multiline command?

In the Windows Command Prompt the ^ is used to escape the next character on the command line. (Like \ is used in strings.) Characters that need to be used in the command line as they are should have a ^ prefixed to them, hence that's why it works for the newline.

For reference the characters that need escaping (if specified as command arguments and not within quotes) are: &|()

So the equivalent of your linux example would be (the More? being a prompt):

C:\> dir ^
More? C:\Windows

What is the best way to implement nested dictionaries?

As others have suggested, a relational database could be more useful to you. You can use a in-memory sqlite3 database as a data structure to create tables and then query them.

import sqlite3

c = sqlite3.Connection(':memory:')
c.execute('CREATE TABLE jobs (state, county, title, count)')

c.executemany('insert into jobs values (?, ?, ?, ?)', [
    ('New Jersey', 'Mercer County',    'Programmers', 81),
    ('New Jersey', 'Mercer County',    'Plumbers',     3),
    ('New Jersey', 'Middlesex County', 'Programmers', 81),
    ('New Jersey', 'Middlesex County', 'Salesmen',    62),
    ('New York',   'Queens County',    'Salesmen',    36),
    ('New York',   'Queens County',    'Plumbers',     9),
])

# some example queries
print list(c.execute('SELECT * FROM jobs WHERE county = "Queens County"'))
print list(c.execute('SELECT SUM(count) FROM jobs WHERE title = "Programmers"'))

This is just a simple example. You could define separate tables for states, counties and job titles.

Adding a Scrollable JTextArea (Java)

  1. Open design view
  2. Right click to textArea
  3. open surround with option
  4. select "...JScrollPane".

Visual Studio loading symbols

Configure in Tools, Options, Debugging, Symbols.

You can watch the output window (view, output) to see what it's doing usually. If it's really slow that probably means it's hitting a symbol server, probably Microsoft's, to download missing symbols. This takes three HTTP hits for each file it can't find on every startup - you can sometimes see this in the status bar at the bottom or in e.g. Fiddler. You can see which modules have loaded symbols in Debug, Windows, Modules whilst you're debugging.

Symbols mean you get useful stack trace information into third party and system assemblies. You definitely need them for your own code, but I think those get loaded regardless. Your best bet is to turn off any non-local symbol sources in that menu and, if you're loading lots of symbols for system assemblies that you don't need to debug into you can temporarily disable loading those to speed up debug start - but they're often useful to have loaded.

How do I join two SQLite tables in my Android application?

An alternate way is to construct a view which is then queried just like a table. In many database managers using a view can result in better performance.

CREATE VIEW xyz SELECT q.question, a.alternative  
   FROM tbl_question AS q, tbl_alternative AS a
  WHERE q.categoryid = a.categoryid 
    AND q._id = a.questionid;

This is from memory so there may be some syntactic issues. http://www.sqlite.org/lang_createview.html

I mention this approach because then you can use SQLiteQueryBuilder with the view as you implied that it was preferred.

java get file size efficiently

Well, I tried to measure it up with the code below:

For runs = 1 and iterations = 1 the URL method is fastest most times followed by channel. I run this with some pause fresh about 10 times. So for one time access, using the URL is the fastest way I can think of:

LENGTH sum: 10626, per Iteration: 10626.0

CHANNEL sum: 5535, per Iteration: 5535.0

URL sum: 660, per Iteration: 660.0

For runs = 5 and iterations = 50 the picture draws different.

LENGTH sum: 39496, per Iteration: 157.984

CHANNEL sum: 74261, per Iteration: 297.044

URL sum: 95534, per Iteration: 382.136

File must be caching the calls to the filesystem, while channels and URL have some overhead.

Code:

import java.io.*;
import java.net.*;
import java.util.*;

public enum FileSizeBench {

    LENGTH {
        @Override
        public long getResult() throws Exception {
            File me = new File(FileSizeBench.class.getResource(
                    "FileSizeBench.class").getFile());
            return me.length();
        }
    },
    CHANNEL {
        @Override
        public long getResult() throws Exception {
            FileInputStream fis = null;
            try {
                File me = new File(FileSizeBench.class.getResource(
                        "FileSizeBench.class").getFile());
                fis = new FileInputStream(me);
                return fis.getChannel().size();
            } finally {
                fis.close();
            }
        }
    },
    URL {
        @Override
        public long getResult() throws Exception {
            InputStream stream = null;
            try {
                URL url = FileSizeBench.class
                        .getResource("FileSizeBench.class");
                stream = url.openStream();
                return stream.available();
            } finally {
                stream.close();
            }
        }
    };

    public abstract long getResult() throws Exception;

    public static void main(String[] args) throws Exception {
        int runs = 5;
        int iterations = 50;

        EnumMap<FileSizeBench, Long> durations = new EnumMap<FileSizeBench, Long>(FileSizeBench.class);

        for (int i = 0; i < runs; i++) {
            for (FileSizeBench test : values()) {
                if (!durations.containsKey(test)) {
                    durations.put(test, 0l);
                }
                long duration = testNow(test, iterations);
                durations.put(test, durations.get(test) + duration);
                // System.out.println(test + " took: " + duration + ", per iteration: " + ((double)duration / (double)iterations));
            }
        }

        for (Map.Entry<FileSizeBench, Long> entry : durations.entrySet()) {
            System.out.println();
            System.out.println(entry.getKey() + " sum: " + entry.getValue() + ", per Iteration: " + ((double)entry.getValue() / (double)(runs * iterations)));
        }

    }

    private static long testNow(FileSizeBench test, int iterations)
            throws Exception {
        long result = -1;
        long before = System.nanoTime();
        for (int i = 0; i < iterations; i++) {
            if (result == -1) {
                result = test.getResult();
                //System.out.println(result);
            } else if ((result = test.getResult()) != result) {
                 throw new Exception("variance detected!");
             }
        }
        return (System.nanoTime() - before) / 1000;
    }

}

Convert JavaScript string in dot notation into an object reference

Here is my code without using eval. Its easy to understand too.

function value(obj, props) {
  if (!props) return obj;
  var propsArr = props.split('.');
  var prop = propsArr.splice(0, 1);
  return value(obj[prop], propsArr.join('.'));
}

var obj = { a: { b: '1', c: '2', d:{a:{b:'blah'}}}};

console.log(value(obj, 'a.d.a.b')); //returns blah

Aligning rotated xticklabels with their respective xticks

If you dont want to modify the xtick labels, you can just use:

plt.xticks(rotation=45)

How to append multiple values to a list in Python

letter = ["a", "b", "c", "d"]
letter.extend(["e", "f", "g", "h"])
letter.extend(("e", "f", "g", "h"))
print(letter)
... 
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h']
    

How to create a property for a List<T>

You could do this but the T generic parameter needs to be declared at the containing class:

public class Foo<T>
{
    public List<T> NewList { get; set; }
}

How to change the output color of echo in Linux

You can use the awesome tput command (suggested in Ignacio's answer) to produce terminal control codes for all kinds of things.


Usage

Specific tput sub-commands are discussed later.

Direct

Call tput as part of a sequence of commands:

tput setaf 1; echo "this is red text"

Use ; instead of && so if tput errors the text still shows.

Shell variables

Another option is to use shell variables:

red=`tput setaf 1`
green=`tput setaf 2`
reset=`tput sgr0`
echo "${red}red text ${green}green text${reset}"

tput produces character sequences that are interpreted by the terminal as having a special meaning. They will not be shown themselves. Note that they can still be saved into files or processed as input by programs other than the terminal.

Command substitution

It may be more convenient to insert tput's output directly into your echo strings using command substitution:

echo "$(tput setaf 1)Red text $(tput setab 7)and white background$(tput sgr 0)"

Example

The above command produces this on Ubuntu:

Screenshot of colour terminal text


Foreground & background colour commands

tput setab [1-7] # Set the background colour using ANSI escape
tput setaf [1-7] # Set the foreground colour using ANSI escape

Colours are as follows:

Num  Colour    #define         R G B

0    black     COLOR_BLACK     0,0,0
1    red       COLOR_RED       1,0,0
2    green     COLOR_GREEN     0,1,0
3    yellow    COLOR_YELLOW    1,1,0
4    blue      COLOR_BLUE      0,0,1
5    magenta   COLOR_MAGENTA   1,0,1
6    cyan      COLOR_CYAN      0,1,1
7    white     COLOR_WHITE     1,1,1

There are also non-ANSI versions of the colour setting functions (setb instead of setab, and setf instead of setaf) which use different numbers, not given here.

Text mode commands

tput bold    # Select bold mode
tput dim     # Select dim (half-bright) mode
tput smul    # Enable underline mode
tput rmul    # Disable underline mode
tput rev     # Turn on reverse video mode
tput smso    # Enter standout (bold) mode
tput rmso    # Exit standout mode

Cursor movement commands

tput cup Y X # Move cursor to screen postion X,Y (top left is 0,0)
tput cuf N   # Move N characters forward (right)
tput cub N   # Move N characters back (left)
tput cuu N   # Move N lines up
tput ll      # Move to last line, first column (if no cup)
tput sc      # Save the cursor position
tput rc      # Restore the cursor position
tput lines   # Output the number of lines of the terminal
tput cols    # Output the number of columns of the terminal

Clear and insert commands

tput ech N   # Erase N characters
tput clear   # Clear screen and move the cursor to 0,0
tput el 1    # Clear to beginning of line
tput el      # Clear to end of line
tput ed      # Clear to end of screen
tput ich N   # Insert N characters (moves rest of line forward!)
tput il N    # Insert N lines

Other commands

tput sgr0    # Reset text format to the terminal's default
tput bel     # Play a bell

With compiz wobbly windows, the bel command makes the terminal wobble for a second to draw the user's attention.


Scripts

tput accepts scripts containing one command per line, which are executed in order before tput exits.

Avoid temporary files by echoing a multiline string and piping it:

echo -e "setf 7\nsetb 1" | tput -S  # set fg white and bg red

See also

  • See man 1 tput
  • See man 5 terminfo for the complete list of commands and more details on these options. (The corresponding tput command is listed in the Cap-name column of the huge table that starts at line 81.)

Nested jQuery.each() - continue/break

Confirm in API documentation http://api.jquery.com/jQuery.each/ say:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

and this is my example http://jsfiddle.net/r6jqP/

(function($){
    $('#go').on('click',function(){
        var i=0,
            all=0;
        $('li').each(function(){
             all++;
             if($('#mytext').val()=='continue')return true;
             i++;
             if($('#mytext').val()==$(this).html()){
                 return false;
             }
        });
        alert('Iterazione : '+i+' to '+all);
    });
}(jQuery));

How to solve "Fatal error: Class 'MySQLi' not found"?

In addition to uncommenting the php_mysqli.dll extension in php.ini, also uncomment the extension_dir directive in php.ini and specify your location:

extension_dir = "C:\software\php\dist\ext"

This made it work for me.

How to add spacing between UITableViewCell

I was in the same boat. At first I tried switching to sections, but in my case it ended up being more of a headache than I originally thought, so I've been looking for an alternative. To keep using rows (and not mess with how you access your model data), here's what worked for me just by using a mask:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
{
    let verticalPadding: CGFloat = 8

    let maskLayer = CALayer()
    maskLayer.cornerRadius = 10    //if you want round edges
    maskLayer.backgroundColor = UIColor.black.cgColor
    maskLayer.frame = CGRect(x: cell.bounds.origin.x, y: cell.bounds.origin.y, width: cell.bounds.width, height: cell.bounds.height).insetBy(dx: 0, dy: verticalPadding/2)
    cell.layer.mask = maskLayer
}

All you have left to do is make the cell's height bigger by the same value as your desired verticalPadding, and then modify your inner layout so that any views that had spacing to the edges of the cell have that same spacing increased by verticalPadding/2. Minor downside: you get verticalPadding/2 padding on both the top and bottom of the tableView, but you can quickly fix this by setting tableView.contentInset.bottom = -verticalPadding/2 and tableView.contentInset.top = -verticalPadding/2. Hope this helps somebody!

Make xargs handle filenames that contain spaces

Given the specific title of this post, here's my suggestion:

ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g'

The idea is to convert blanks to any unique character, like '<', and then change that into '\ ', a backslash followed by a blank. You can then pipe that into any command you like, such as:

ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g' | xargs -L1 GetFileInfo

The key here lies in the 'tr' and 'sed' commands; and you can use any character besides '<', such as '?' or even a tab-character.

How do I check out an SVN project into Eclipse as a Java project?

Here are the steps:

  • Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: http://subclipse.tigris.org/install.html
  • Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
  • Select your project's root folder and select checkout as a project in the workspace.

It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),

XML element with attribute and content using JAXB

Here is working solution:

Output:

public class XmlTest {

    private static final Logger log = LoggerFactory.getLogger(XmlTest.class);

    @Test
    public void createDefaultBook() throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
        Marshaller marshaller = jaxbContext.createMarshaller();

        StringWriter writer = new StringWriter();
        marshaller.marshal(new Book(), writer);

        log.debug("Book xml:\n {}", writer.toString());
    }


    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlRootElement(name = "book")
    public static class Book {

        @XmlElementRef(name = "price")
        private Price price = new Price();


    }

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlRootElement(name = "price")
    public static class Price {
        @XmlAttribute(name = "drawable")
        private Boolean drawable = true; //you may want to set default value here

        @XmlValue
        private int priceValue = 1234;

        public Boolean getDrawable() {
            return drawable;
        }

        public void setDrawable(Boolean drawable) {
            this.drawable = drawable;
        }

        public int getPriceValue() {
            return priceValue;
        }

        public void setPriceValue(int priceValue) {
            this.priceValue = priceValue;
        }
    }
}

Output:

22:00:18.471 [main] DEBUG com.grebski.stack.XmlTest - Book xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
    <price drawable="true">1234</price>
</book>

JPA Hibernate One-to-One relationship

I have a better way of doing this:

@Entity
public class Person {

    @OneToOne(cascade={javax.persistence.CascadeType.ALL})
    @JoinColumn(name = "`Id_OtherInfo`")
    public OtherInfo getOtherInfo() {
      return otherInfo;
    }

}

That's all

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

following below steps will fix this issue,

  1. Download the CA Certificate from this link: https://curl.haxx.se/ca/cacert.pem
  2. Find and open php.ini
  3. Look for curl.cainfo and paste the absolute path where you have download the Certificate. curl.cainfo ="C:\wamp\htdocs\cert\cacert.pem"
  4. Restart WAMP/XAMPP (apache server).
  5. It works!

hope that helps !!

psql: command not found Mac

If Postgres was downloaded and installed, running this should fix the issue:

sudo mkdir -p /etc/paths.d &&
echo /Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee 
/etc/paths.d/postgresapp

Restart the terminal and you'll be able to use psql command.

Ref: https://postgresapp.com/documentation/cli-tools.html

Remove and Replace Printed items

One way is to use ANSI escape sequences:

import sys
import time
for i in range(10):
    print("Loading" + "." * i)
    sys.stdout.write("\033[F") # Cursor up one line
    time.sleep(1)

Also sometimes useful (for example if you print something shorter than before):

sys.stdout.write("\033[K") # Clear to the end of line

Properly embedding Youtube video into bootstrap 3.0 page

This works fine for me...

   .delimitador{
        width:100%;
        margin:auto;
    }
    .contenedor{
        height:0px;
        width:100%;
        /*max-width:560px; /* Así establecemos el ancho máximo (si lo queremos) */
        padding-top:56.25%; /* Relación: 16/9 = 56.25% */
        position:relative;
    }

    iframe{
            position:absolute;
            height:100%;
            width:100%;
            top:0px;
            left:0px;
    }

and then

<div class="delimitador">
<div class="contenedor">
// youtube code 
</div>
</div>

Get week of year in JavaScript like in PHP

I tried a lot to get the shortest code to get the weeknumber ISO-conform.

Date.prototype.getWeek=function(){
    var date=new Date(this);
    date.setHours(0,0,0,0);
    return Math.round(((date.setDate(this.getDate()+2-(this.getDay()||7))-date.setMonth(0,4))/8.64e7+3+(date.getDay()||7))/7)+"/"+date.getFullYear();}

The variable date is necessary to avoid to alter the original this. I used the return values of setDate() and setMonth() to dispense with getTime() to save code length and I used an expontial number for milliseconds of a day instead of a multiplication of single elements or a number with five zeros. this is Date or Number of milliseconds, return value is String e.g. "49/2017".

Remove specific characters from a string in Python

you can use set

    charlist = list(set(string.digits+string.ascii_uppercase) - set('10IO'))
    return ''.join([random.SystemRandom().choice(charlist) for _ in range(passlen)])

SQL Server stored procedure parameters

SQL Server doesn't allow you to pass parameters to a procedure that you haven't defined. I think the closest you can get to this sort of design is to use optional parameters like so:

CREATE PROCEDURE GetTaskEvents
    @TaskName varchar(50),
    @ID int = NULL
AS
BEGIN
-- SP Logic
END;

You would need to include every possible parameter that you might use in the definition. Then you'd be free to call the procedure either way:

EXEC GetTaskEvents @TaskName = 'TESTTASK', @ID = 2;
EXEC GetTaskEvents @TaskName = 'TESTTASK'; -- @ID gets NULL here

C# Wait until condition is true

you can use SpinUntil which is buildin in the .net-framework. Please note: This method causes high cpu-workload.

How to force the input date format to dd/mm/yyyy?

DEMO : http://jsfiddle.net/shfj70qp/

//dd/mm/yyyy 

var date = new Date();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();

console.log(month+"/"+day+"/"+year);

C# DropDownList with a Dictionary as DataSource

Like that you can set DataTextField and DataValueField of DropDownList using "Key" and "Value" texts :

    Dictionary<string, string> list = new Dictionary<string, string>();
    list.Add("item 1", "Item 1");
    list.Add("item 2", "Item 2");
    list.Add("item 3", "Item 3");
    list.Add("item 4", "Item 4");

    ddl.DataSource = list;
    ddl.DataTextField = "Value";
    ddl.DataValueField = "Key";
    ddl.DataBind();

Can't connect Nexus 4 to adb: unauthorized

This kind of an old post and in most cases I think the answer that has been upvoted the most will work for people.

In Lollipop on a GPE HTC M8 I was still having problems. The below steps worked for me.

  1. Go to Settings
  2. Tap on Storage
  3. Tap on 3 dots in the top right
  4. Tap on USB Computer Connection
  5. UNCHECK MTP
  6. UNCHECK PTP
  7. Back in your console, type adb devices

Now you should get the RSA popup on your phone.

How to generate service reference with only physical wsdl file

This may be the easiest method

  • Right click on the project and select "Add Service Reference..."
  • In the Address: box, enter the physical path (C:\test\project....) of the downloaded/Modified wsdl.
  • Hit Go

How to vertically center content with variable height within a div?

This is something I have needed to do many times and a consistent solution still requires you add a little non-semantic markup and some browser specific hacks. When we get browser support for css 3 you'll get your vertical centering without sinning.

For a better explanation of the technique you can look the article I adapted it from, but basically it involves adding an extra element and applying different styles in IE and browsers that support position:table\table-cell on non-table elements.

<div class="valign-outer">
    <div class="valign-middle">
        <div class="valign-inner">
            Excuse me. What did you sleep in your clothes again last night. Really. You're gonna be in the car with her. Hey, not too early I sleep in on Saturday. Oh, McFly, your shoe's untied. Don't be so gullible, McFly. You got the place fixed up nice, McFly. I have you're car towed all the way to your house and all you've got for me is light beer. What are you looking at, butthead. Say hi to your mom for me.
        </div>
    </div>
</div>

<style>
    /* Non-structural styling */
    .valign-outer { height: 400px; border: 1px solid red; }
    .valign-inner { border: 1px solid blue; }
</style>

<!--[if lte IE 7]>
<style>
    /* For IE7 and earlier */
    .valign-outer { position: relative; overflow: hidden; }
    .valign-middle { position: absolute; top: 50%; }
    .valign-inner { position: relative; top: -50% }
</style>
<![endif]-->
<!--[if gt IE 7]> -->
<style>
    /* For other browsers */
    .valign-outer { position: static; display: table; overflow: hidden; }
    .valign-middle { position: static; display: table-cell; vertical-align: middle; width: 100%; }
</style>

There are many ways (hacks) to apply styles in specific sets of browsers. I used conditional comments but look at the article linked above to see two other techniques.

Note: There are simple ways to get vertical centering if you know some heights in advance, if you are trying to center a single line of text, or in several other cases. If you have more details then throw them in because there may be a method that doesn't require browser hacks or non-semantic markup.

Update: We are beginning to get better browser support for CSS3, bringing both flex-box and transforms as alternative methods for getting vertical centering (among other effects). See this other question for more information about modern methods, but keep in mind that browser support is still sketchy for CSS3.

Javascript select onchange='this.form.submit()'

My psychic debugging skills tell me that your submit button is named submit.
Therefore, form.submit refers to the button rather than the method.

Rename the button to something else so that form.submit refers to the method again.

Drawing in Java using Canvas

Suggestions:

  • Don't use Canvas as you shouldn't mix AWT with Swing components unnecessarily.
  • Instead use a JPanel or JComponent.
  • Don't get your Graphics object by calling getGraphics() on a component as the Graphics object obtained will be transient.
  • Draw in the JPanel's paintComponent() method.
  • All this is well explained in several tutorials that are easily found. Why not read them first before trying to guess at this stuff?

Key tutorial links:

How to log out user from web site using BASIC authentication?

_x000D_
_x000D_
    function logout(secUrl, redirUrl) {_x000D_
        if (bowser.msie) {_x000D_
            document.execCommand('ClearAuthenticationCache', 'false');_x000D_
        } else if (bowser.gecko) {_x000D_
            $.ajax({_x000D_
                async: false,_x000D_
                url: secUrl,_x000D_
                type: 'GET',_x000D_
                username: 'logout'_x000D_
            });_x000D_
        } else if (bowser.webkit) {_x000D_
            var xmlhttp = new XMLHttpRequest();_x000D_
            xmlhttp.open("GET", secUrl, true);_x000D_
            xmlhttp.setRequestHeader("Authorization", "Basic logout");_x000D_
            xmlhttp.send();_x000D_
        } else {_x000D_
            alert("Logging out automatically is unsupported for " + bowser.name_x000D_
                + "\nYou must close the browser to log out.");_x000D_
        }_x000D_
        setTimeout(function () {_x000D_
            window.location.href = redirUrl;_x000D_
        }, 200);_x000D_
    }
_x000D_
_x000D_
_x000D_

I tried using the above in the following way.

?php
    ob_start();
    session_start();
    require_once 'dbconnect.php';

    // if session is not set this will redirect to login page
    if( !isset($_SESSION['user']) ) {
        header("Location: index.php");
        exit;
    }
    // select loggedin users detail
    $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
    $userRow=mysql_fetch_array($res);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome - <?php echo $userRow['userEmail']; ?></title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css"  />
<link rel="stylesheet" href="style.css" type="text/css" />

    <script src="assets/js/bowser.min.js"></script>
<script>
//function logout(secUrl, redirUrl)
//bowser = require('bowser');
function logout(secUrl, redirUrl) {
alert(redirUrl);
    if (bowser.msie) {
        document.execCommand('ClearAuthenticationCache', 'false');
    } else if (bowser.gecko) {
        $.ajax({
            async: false,
            url: secUrl,
            type: 'GET',
            username: 'logout'
        });
    } else if (bowser.webkit) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", secUrl, true);
        xmlhttp.setRequestHeader("Authorization", "Basic logout");
        xmlhttp.send();
    } else {
        alert("Logging out automatically is unsupported for " + bowser.name
            + "\nYou must close the browser to log out.");
    }
    window.location.assign(redirUrl);
    /*setTimeout(function () {
        window.location.href = redirUrl;
    }, 200);*/
}


function f1()
    {
       alert("f1 called");
       //form validation that recalls the page showing with supplied inputs.    
    }
</script>
</head>
<body>

    <nav class="navbar navbar-default navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="http://www.codingcage.com">Coding Cage</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="http://www.codingcage.com/2015/01/user-registration-and-login-script-using-php-mysql.html">Back to Article</a></li>
            <li><a href="http://www.codingcage.com/search/label/jQuery">jQuery</a></li>
            <li><a href="http://www.codingcage.com/search/label/PHP">PHP</a></li>
          </ul>
          <ul class="nav navbar-nav navbar-right">

            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
              <span class="glyphicon glyphicon-user"></span>&nbsp;Hi' <?php echo $userRow['userEmail']; ?>&nbsp;<span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="logout.php?logout"><span class="glyphicon glyphicon-log-out"></span>&nbsp;Sign Out</a></li>
              </ul>
            </li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav> 

    <div id="wrapper">

    <div class="container">

        <div class="page-header">
        <h3>Coding Cage - Programming Blog</h3>
        </div>

        <div class="row">
        <div class="col-lg-12" id="div_logout">
        <h1 onclick="logout(window.location.href, 'www.espncricinfo.com')">MichaelA1S1! Click here to see log out functionality upon click inside div</h1>
        </div>
        </div>

    </div>

    </div>

    <script src="assets/jquery-1.11.3-jquery.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>


</body>
</html>
<?php ob_end_flush(); ?>

But it only redirects you to new location. No logout.

What causes a java.lang.StackOverflowError

What is java.lang.StackOverflowError

The error java.lang.StackOverflowError is thrown to indicate that the application’s stack was exhausted, due to deep recursion i.e your program/script recurses too deeply.

Details

The StackOverflowError extends VirtualMachineError class which indicates that the JVM have been or have run out of resources and cannot operate further. The VirtualMachineError which extends the Error class is used to indicate those serious problems that an application should not catch. A method may not declare such errors in its throw clause because these errors are abnormal conditions that was never expected to occur.

An Example

Minimal, Complete, and Verifiable Example :

package demo;

public class StackOverflowErrorExample {

    public static void main(String[] args) 
    {
        StackOverflowErrorExample.recursivePrint(1);
    }

    public static void recursivePrint(int num) {
        System.out.println("Number: " + num);

        if(num == 0)
            return;
        else
            recursivePrint(++num);
    }

}

Console Output

Number: 1
Number: 2
.
.
.
Number: 8645
Number: 8646
Number: 8647Exception in thread "main" java.lang.StackOverflowError
    at java.io.FileOutputStream.write(Unknown Source)
    at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
    at java.io.BufferedOutputStream.flush(Unknown Source)
    at java.io.PrintStream.write(Unknown Source)
    at sun.nio.cs.StreamEncoder.writeBytes(Unknown Source)
    at sun.nio.cs.StreamEncoder.implFlushBuffer(Unknown Source)
    at sun.nio.cs.StreamEncoder.flushBuffer(Unknown Source)
    at java.io.OutputStreamWriter.flushBuffer(Unknown Source)
    at java.io.PrintStream.newLine(Unknown Source)
    at java.io.PrintStream.println(Unknown Source)
    at demo.StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:11)
    at demo.StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:16)
    .
    .
    .
    at demo.StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:16)

Explaination

When a function call is invoked by a Java Application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no space for a new stack frame then, the StackOverflowError is thrown by the Java Virtual Machine (JVM).

The most common case that can possibly exhaust a Java application’s stack is recursion. In recursion, a method invokes itself during its execution. Recursion one of the most powerful general-purpose programming technique, but must be used with caution, in order for the StackOverflowError to be avoided.

References

How to convert float number to Binary?

(d means decimal, b means binary)

  1. 12.25d is your float.
  2. You write 12d in binary and remove it from your float. Only the remainder (.25d) will be left.
  3. You write the dot.
  4. While the remainder (0.25d) is not zero (and/or you want more digits), multiply it with 2 (-> 0.50d), remove and write the digit left of the dot (0), and continue with the new remainder (.50d).

Style child element when hover on parent

Yes, you can do this use this below code it may help you.

_x000D_
_x000D_
.parentDiv{_x000D_
margin : 25px;_x000D_
_x000D_
}_x000D_
.parentDiv span{_x000D_
  display : block;_x000D_
  padding : 10px;_x000D_
  text-align : center;_x000D_
  border: 5px solid #000;_x000D_
  margin : 5px;_x000D_
}_x000D_
_x000D_
.parentDiv div{_x000D_
padding:30px;_x000D_
border: 10px solid green;_x000D_
display : inline-block;_x000D_
align : cente;_x000D_
}_x000D_
_x000D_
.parentDiv:hover{_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv1{_x000D_
border: 10px solid red;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv2{_x000D_
border: 10px solid yellow;_x000D_
} _x000D_
.parentDiv:hover .childDiv3{_x000D_
border: 10px solid orange;_x000D_
}
_x000D_
<div class="parentDiv">_x000D_
<span>Hover me to change Child Div colors</span>_x000D_
  <div class="childDiv1">_x000D_
    First Div Child_x000D_
  </div>_x000D_
  <div class="childDiv2">_x000D_
    Second Div Child_x000D_
  </div>_x000D_
  <div class="childDiv3">_x000D_
    Third Div Child_x000D_
  </div>_x000D_
  <div class="childDiv4">_x000D_
    Fourth Div Child_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get installed applications in a system

Might I suggest you take a look at WMI (Windows Management Instrumentation). If you add the System.Management reference to your C# project, you'll gain access to the class `ManagementObjectSearcher', which you will probably find useful.

There are various WMI Classes for Installed Applications, but if it was installed with Windows Installer, then the Win32_Product class is probably best suited to you.

ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT * FROM Win32_Product");

In nodeJs is there a way to loop through an array without using array size?

Use Iterators...

var myarray = ['hello', ' hello again'];
processArray(myarray[Symbol.iterator](), () => {
    console.log('all done')
})
function processArray(iter, cb) {
    var curr = iter.next()
    if(curr.done)
        return cb()
    console.log(curr.value)
    processArray(iter, cb)
}

More in depth overview: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

Confused about __str__ on list in Python

Because of the infinite superiority of Python over Java, Python has not one, but two toString operations.

One is __str__, the other is __repr__

__str__ will return a human readable string. __repr__ will return an internal representation.

__repr__ can be invoked on an object by calling repr(obj) or by using backticks `obj`.

When printing lists as well as other container classes, the contained elements will be printed using __repr__.

REST API 404: Bad URI, or Missing Resource?

404 is just the HTTP response code. On top of that, you can provide a response body and/or other headers with a more meaningful error message that developers will see.

How do I URL encode a string

Apple's advice, in the 10.11 release notes, is:

If you need to percent-encode an entire URL string, you can use this code to encode a NSString intended to be a URL (in urlStringToEncode):

NSString *percentEncodedURLString =
  [[NSURL URLWithDataRepresentation:[urlStringToEncode dataUsingEncoding:NSUTF8StringEncoding] relativeToURL:nil] relativeString];

Express-js can't GET my static files, why?

I have the same problem. I have resolved the problem with following code:

app.use('/img',express.static(path.join(__dirname, 'public/images')));
app.use('/js',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/css',express.static(path.join(__dirname, 'public/stylesheets')));

Static request example:

http://pruebaexpress.lite.c9.io/js/socket.io.js

I need a more simple solution. Does it exist?

python: changing row index of pandas data frame

you can do

followers_df.index = range(20)

Using .NET, how can you find the mime type of a file based on the file signature not the extension

I use an hybrid solution:

    using System.Runtime.InteropServices;

    [DllImport (@"urlmon.dll", CharSet = CharSet.Auto)]
    private extern static System.UInt32 FindMimeFromData(
        System.UInt32 pBC, 
        [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
        [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
        System.UInt32 cbSize,
        [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
        System.UInt32 dwMimeFlags,
        out System.UInt32 ppwzMimeOut,
        System.UInt32 dwReserverd
    );

    private string GetMimeFromRegistry (string Filename)
    {
        string mime = "application/octetstream";
        string ext = System.IO.Path.GetExtension(Filename).ToLower();
        Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
        if (rk != null && rk.GetValue("Content Type") != null)
            mime = rk.GetValue("Content Type").ToString();
        return mime;
    }

    public string GetMimeTypeFromFileAndRegistry (string filename)
    {
        if (!File.Exists(filename))
        {
           return GetMimeFromRegistry (filename);
        }

        byte[] buffer = new byte[256];

        using (FileStream fs = new FileStream(filename, FileMode.Open))
        {
            if (fs.Length >= 256)
                fs.Read(buffer, 0, 256);
            else
                fs.Read(buffer, 0, (int)fs.Length);
        }

        try
        {            
            System.UInt32 mimetype;

            FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);

            System.IntPtr mimeTypePtr = new IntPtr(mimetype);

            string mime = Marshal.PtrToStringUni(mimeTypePtr);

            Marshal.FreeCoTaskMem(mimeTypePtr);

            if (string.IsNullOrWhiteSpace (mime) || 
                mime =="text/plain" || mime == "application/octet-stream")                    
            {
                return GetMimeFromRegistry (filename);
            }

            return mime;
        }
        catch (Exception e)
        {
            return GetMimeFromRegistry (filename);
        }
    }

How to bind an enum to a combobox control in WPF?

I just kept it simple. I created a list of items with the enum values in my ViewModel:

public enum InputsOutputsBoth
{
    Inputs,
    Outputs,
    Both
}

private IList<InputsOutputsBoth> _ioTypes = new List<InputsOutputsBoth>() 
{ 
    InputsOutputsBoth.Both, 
    InputsOutputsBoth.Inputs, 
    InputsOutputsBoth.Outputs 
};

public IEnumerable<InputsOutputsBoth> IoTypes
{
    get { return _ioTypes; }
    set { }
}

private InputsOutputsBoth _selectedIoType;

public InputsOutputsBoth SelectedIoType
{
    get { return _selectedIoType; }
    set
    {
        _selectedIoType = value;
        OnPropertyChanged("SelectedIoType");
        OnSelectionChanged();
    }
}

In my xaml code I just need this:

<ComboBox ItemsSource="{Binding IoTypes}" SelectedItem="{Binding SelectedIoType, Mode=TwoWay}">

Connecting PostgreSQL 9.2.1 with Hibernate

This is the hibernate.cfg.xml file to connect postgresql 9.5 and this is help to you basic configuration.

 <?xml version='1.0' encoding='utf-8'?>

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration
>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.url">jdbc:postgresql://localhost:5433/hibernatedb</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">password</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.waseem.UserDetails"/>
    </session-factory>
</hibernate-configuration>

Make sure File Location should be under src/main/resources/hibernate.cfg.xml

PHP absolute path to root

This is my way to find the rootstart. Create at ROOT start a file with name mainpath.php

<?php 
## DEFINE ROOTPATH
$check_data_exist = ""; 

$i_surf = 0;

// looking for mainpath.php at the aktiv folder or higher folder

while (!file_exists($check_data_exist."mainpath.php")) {
  $check_data_exist .= "../"; 
  $i_surf++;
  // max 7 folder deep
  if ($i_surf == 7) { 
   return false;
  }
}

define("MAINPATH", ($check_data_exist ? $check_data_exist : "")); 
?>

For me is that the best and easiest way to find them. ^^

Link error "undefined reference to `__gxx_personality_v0'" and g++

It sounds like you're trying to link with your resulting object file with gcc instead of g++:

Note that programs using C++ object files must always be linked with g++, in order to supply the appropriate C++ libraries. Attempting to link a C++ object file with the C compiler gcc will cause "undefined reference" errors for C++ standard library functions:

$ g++ -Wall -c hello.cc
$ gcc hello.o       (should use g++)
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
.....
hello.o(.eh_frame+0x11):
  undefined reference to `__gxx_personality_v0'

Source: An Introduction to GCC - for the GNU compilers gcc and g++

How to restart VScode after editing extension's config?

  1. Open the Command Palette

    Ctrl + Shift + P

  2. Then type:

    Reload Window
    

Difference between | and || or & and && for comparison

& and | are bitwise operators that can operate on both integer and Boolean arguments, and && and || are logical operators that can operate only on Boolean arguments. In many languages, if both arguments are Boolean, the key difference is that the logical operators will perform short circuit evaluation and not evaluate the second argument if the first argument is enough to determine the answer (e.g. in the case of &&, if the first argument is false, the second argument is irrelevant).

mongodb count num of distinct values per field/key

You can leverage on Mongo Shell Extensions. It's a single .js import that you can append to your $HOME/.mongorc.js, or programmatically, if you're coding in Node.js/io.js too.

Sample

For each distinct value of field counts the occurrences in documents optionally filtered by query

> db.users.distinctAndCount('name', {name: /^a/i})

{
  "Abagail": 1,
  "Abbey": 3,
  "Abbie": 1,
  ...
}

The field parameter could be an array of fields

> db.users.distinctAndCount(['name','job'], {name: /^a/i})

{
  "Austin,Educator" : 1,
  "Aurelia,Educator" : 1,
  "Augustine,Carpenter" : 1,
  ...
}

When should I really use noexcept?

When can I realistically except to observe a performance improvement after using noexcept? In particular, give an example of code for which a C++ compiler is able to generate better machine code after the addition of noexcept.

Um, never? Is never a time? Never.

noexcept is for compiler performance optimizations in the same way that const is for compiler performance optimizations. That is, almost never.

noexcept is primarily used to allow "you" to detect at compile-time if a function can throw an exception. Remember: most compilers don't emit special code for exceptions unless it actually throws something. So noexcept is not a matter of giving the compiler hints about how to optimize a function so much as giving you hints about how to use a function.

Templates like move_if_noexcept will detect if the move constructor is defined with noexcept and will return a const& instead of a && of the type if it is not. It's a way of saying to move if it is very safe to do so.

In general, you should use noexcept when you think it will actually be useful to do so. Some code will take different paths if is_nothrow_constructible is true for that type. If you're using code that will do that, then feel free to noexcept appropriate constructors.

In short: use it for move constructors and similar constructs, but don't feel like you have to go nuts with it.

Copy files without overwrite

Here it is in batch file form:

@echo off
set source=%1
set dest=%2
for %%f in (%source%\*) do if not exist "%dest%\%%~nxf" copy "%%f" "%dest%\%%~nxf"

How to close a window using jQuery

This will only work for windows which are opened by using window.open(); method. Try this

var tmp=window.open(params);
tmp.close();

No resource identifier found for attribute '...' in package 'com.app....'

I solved is by using android:background instead of app:srcCompact.

This is caused by xmlns:app="http://schemas.android.com/apk/res-auto". As people have suggested above, you could use /lib-auto or /lib/your-package but I got suspicious namespace error when I tried using /lib-auto and unexpected namespace prefix error with /lib/my-package .

How to Enable ActiveX in Chrome?

I downloaded this "IE Tab Multi" from Chrome. It works good! http://iblogbox.com/chrome/ietab/alert.php

MongoDB vs. Cassandra

I saw a presentation on mongodb yesterday. I can definitely say that setup was "simple", as simple as unpacking it and firing it up. Done.

I believe that both mongodb and cassandra will run on virtually any regular linux hardware so you should not find to much barrier in that area.

I think in this case, at the end of the day, it will come down to which do you personally feel more comfortable with and which has a toolset that you prefer. As far as the presentation on mongodb, the presenter indicated that the toolset for mongodb was pretty light and that there werent many (they said any really) tools similar to whats available for MySQL. This was of course their experience so YMMV. One thing that I did like about mongodb was that there seemed to be lots of language support for it (Python, and .NET being the two that I primarily use).

The list of sites using mongodb is pretty impressive, and I know that twitter just switched to using cassandra.

How to prevent ENTER keypress to submit a web form?

I've always done it with a keypress handler like the above in the past, but today hit on a simpler solution. The enter key just triggers the first non-disabled submit button on the form, so actually all that's required is to intercept that button trying to submit:

<form>
  <div style="display: none;">
    <input type="submit" name="prevent-enter-submit" onclick="return false;">
  </div>
  <!-- rest of your form markup -->
</form>

That's it. Keypresses will be handled as usual by the browser / fields / etc. If the enter-submit logic is triggered, then the browser will find that hidden submit button and trigger it. And the javascript handler will then prevent the submision.

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

An ideal solution will:

  1. Automatically scale to the width of the navigation container
  2. Support a dynamic number of menu items.

Using a simple ul menu inside of an nav container, we can build a solution that meets the above requirements.

HTML

<nav>
  <ul>
    <li>Home</li>
    <li>About</li>
    <li>Basic Services</li>
    <li>Specialty Services</li>
    <li>Our Staff</li>
    <li>Contact Us</li>
  </ul>
</nav>

First, we need to force the ul to have the full width of its nav container. To accomplish this, we will use the :after psuedo-element with width: 100%.

This achieves our goal perfectly, but adds trailing whitespace from the psuedo-element. We can remove this whitespace across all browsers through IE8 by setting the line-height of the ul to 0 and setting it back to 100% on its li children. See the example CodePen and solution below:

CSS

nav {
  width: 900px;
}

nav ul {
  text-align: justify;
  line-height: 0;
  margin: 0;
  padding: 0;
}

nav ul:after {
  content: '';
  display: inline-block;
  width: 100%;
}

nav ul li {
  display: inline-block;
  line-height: 100%;
}

case statement in SQL, how to return multiple variables?

You can return multiple value inside a xml data type in "case" expression, then extract them, also "else" block is available

SELECT 
xmlcol.value('(value1)[1]', 'NVARCHAR(MAX)') AS value1,
xmlcol.value('(value2)[1]', 'NVARCHAR(MAX)') AS value2
FROM
(SELECT CASE
WHEN <condition 1> THEN
CAST((SELECT a1 AS value1, b1 AS value2 FOR XML PATH('')) AS XML)
WHEN <condition 2> THEN
CAST((SELECT a2 AS value1, b2 AS value2 FOR XML PATH('')) AS XML)
ELSE
CAST((SELECT a3 AS value1, b3 AS value2 FOR XML PATH('')) AS XML)
END AS xmlcol
FROM <table>) AS tmp

Understanding lambda in python and using it to pass multiple arguments

I believe bind always tries to send an event parameter. Try:

self.entry_1.bind("<Return>", lambda event: self.calculate(self.buttonOut_1.grid_info(), 1))

You accept the parameter and never use it.

Maximum execution time in phpMyadmin

I faced the same problem while executing a curl. I got it right when I changed the following in the php.ini file:

max_execution_time = 1000 ;

and also

max_input_time = 1000 ;

Probably your problem should be solved by making above two changes and restarting the apache server.

Even after changing the above the problem persists and if you think it's because of some database operation using mysql you can try changing this also:

mysql.connect_timeout = 1000 ; // this is not neccessary

All this should be changed in php.ini file and apache server should be restarted to see the changes.

How can I programmatically get the MAC address of an iphone

Now iOS 7 devices – are always returning a MAC address of 02:00:00:00:00:00.

So better use [UIDevice identifierForVendor].

so better to call this method to get app specific unique key

Category will more suitable

import "UIDevice+Identifier.h"

- (NSString *) identifierForVendor1
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(identifierForVendor)]) {
        return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    }
    return @"";
}

Now call above method to get unique address

NSString *like_UDID=[NSString stringWithFormat:@"%@",
                [[UIDevice currentDevice] identifierForVendor1]];

NSLog(@"%@",like_UDID);

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

Check that you have both ngModel and name attributes in your select. Also Select is a form component and not the entire form so more logical declaration of local reference will be:-

<div class="form-group">
    <label for="actionType">Action Type</label>
    <select
            ngControl="actionType" 
      ===>  #actionType="ngModel"
            ngModel    // You can go with 1 or 2 way binding as well
            name="actionType"
            id="actionType" 
            class="form-control" 
            required>
            <option value=""></option>
            <option *ngFor="let actionType of actionTypes" value="{{ actionType.label }}">
                {{ actionType.label }}
            </option>
        </select> 
    </div>

One more Important thing is make sure you import either FormsModule in the case of template driven approach or ReactiveFormsModule in the case of Reactive approach. Or you can import both which is also totally fine.

Run react-native application on iOS device directly from command line?

First install the required library globally on your computer:

npm install -g ios-deploy

Go to your settings on your iPhone to find the name of the device.

Then provide that below like:

react-native run-ios --device "______\'s iPhone"

Sometimes this will fail and output a message like this:

Found Xcode project ________.xcodeproj
Could not find device with the name: "_______'s iPhone".
Choose one of the following:
______’s iPhone Udid: _________

That udid is used like this:

react-native run-ios --udid 0412e2c230a14e23451699

Optionally you may use:

react-native run-ios --udid 0412e2c230a14e23451699 -- configuration Release

How to convert JSON object to JavaScript array?

Suppose you have:

var j = {0: "1", 1: "2", 2: "3", 3: "4"};

You could get the values with (supported in practically all browser versions):

Object.keys(j).map(function(_) { return j[_]; })

or simply:

Object.values(j)

Output:

["1", "2", "3", "4"]

Computing cross-correlation function?

For 1D array, numpy.correlate is faster than scipy.signal.correlate, under different sizes, I see a consistent 5x peformance gain using numpy.correlate. When two arrays are of similar size (the bright line connecting the diagonal), the performance difference is even more outstanding (50x +).

# a simple benchmark
res = []
for x in range(1, 1000):
    list_x = []
    for y in range(1, 1000): 

        # generate different sizes of series to compare
        l1 = np.random.choice(range(1, 100), size=x)
        l2 = np.random.choice(range(1, 100), size=y)

        time_start = datetime.now()
        np.correlate(a=l1, v=l2)
        t_np = datetime.now() - time_start

        time_start = datetime.now()
        scipy.signal.correlate(in1=l1, in2=l2)
        t_scipy = datetime.now() - time_start

        list_x.append(t_scipy / t_np)
    res.append(list_x)
plt.imshow(np.matrix(res))

enter image description here

As default, scipy.signal.correlate calculates a few extra numbers by padding and that might explained the performance difference.

>> l1 = [1,2,3,2,1,2,3]
>> l2 = [1,2,3]
>> print(numpy.correlate(a=l1, v=l2))
>> print(scipy.signal.correlate(in1=l1, in2=l2))

[14 14 10 10 14]
[ 3  8 14 14 10 10 14  8  3]  # the first 3 is [0,0,1]dot[1,2,3]

jQuery UI Dialog individual CSS styling

I created custom styles by just overriding jQuery classes in inline style. So on top of the page, you have the jQuery CSS linked and right after that override the classes you need to modify:

<head>
    <link href="/Content/theme/base/jquery.ui.all.css" rel="stylesheet"/>

    <style type="text/css">
        .ui-dialog .ui-dialog-content
        {
            position: relative;
            border: 0;
            padding: .5em 1em;
            background: none;
            overflow: auto;
            zoom: 1;
            background-color: #ffd;
            border: solid 1px #ea7;
        }

        .ui-dialog .ui-dialog-titlebar
        {
            display:none;
        }

        .ui-widget-content
        {
            border:none;
        }
    </style>
</head>

How do I set the focus to the first input element in an HTML form independent from the id?

You should be able to use clientHeight instead of checking for the display attribute, since a parent could be hiding this element:

function setFocus() {
    var forms = document.forms || [];
        for (var i = 0; i < forms.length; i++) {
            for (var j = 0; j < forms[i].length; j++) {
            var widget = forms[i][j];
                if ((widget && widget.domNode && widget.domNode.clientHeight > 0) && typeof widget.focus === "function")
                 && (typeof widget.disabled === "undefined" || widget.disabled === false)
                 && (typeof widget.readOnly === "undefined" || widget.readOnly === false)) {
                        widget.focus();
                        break;
                }
            }
        }
    }   
}

Convert object string to JSON

Using new Function() is better than eval, but still should only be used with safe input.

const parseJSON = obj => Function('"use strict";return (' + obj + ')')();

console.log(parseJSON("{a:(4-1), b:function(){}, c:new Date()}"))
// outputs: Object { a: 3, b: b(), c: Date 2019-06-05T09:55:11.777Z }

Sources: MDN, 2ality

Python - round up to the nearest ten

This will round down correctly as well:

>>> n = 46
>>> rem = n % 10
>>> if rem < 5:
...     n = int(n / 10) * 10
... else:
...     n = int((n + 10) / 10) * 10
...
>>> 50

Git: How to remove proxy

Check your enviroment:

echo $http_proxy
echo $https_proxy
echo $HTTPS_PROXY
echo $HTTP_PROXY

and delete with export http_proxy=

Or check https and http proxy

git config --global --unset https.proxy
git config --global --unset http.proxy

Or do you have the proxy in the local config?

git config --unset http.proxy
git config --unset https.proxy

Up, Down, Left and Right arrow keys do not trigger KeyDown event

protected override bool IsInputKey(Keys keyData)
{
    if (((keyData & Keys.Up) == Keys.Up)
        || ((keyData & Keys.Down) == Keys.Down)
        || ((keyData & Keys.Left) == Keys.Left)
        || ((keyData & Keys.Right) == Keys.Right))
        return true;
    else
        return base.IsInputKey(keyData);
}

Convert int (number) to string with leading zeros? (4 digits)

Use String.PadLeft like this:

var result = input.ToString().PadLeft(length, '0');

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

Closing a Userform with Unload Me doesn't work

It should also be noted that if you have buttons grouped together on your user form that it can link it to a different button in the group despite the one you intended being clicked.

How to clear or stop timeInterval in angularjs?

You can store the promise returned by the interval and use $interval.cancel() to that promise, which cancels the interval of that promise. To delegate the starting and stopping of the interval, you can create start() and stop() functions whenever you want to stop and start them again from a specific event. I have created a snippet below showing the basics of starting and stopping an interval, by implementing it in view through the use of events (e.g. ng-click) and in the controller.

_x000D_
_x000D_
angular.module('app', [])_x000D_
_x000D_
  .controller('ItemController', function($scope, $interval) {_x000D_
  _x000D_
    // store the interval promise in this variable_x000D_
    var promise;_x000D_
  _x000D_
    // simulated items array_x000D_
    $scope.items = [];_x000D_
    _x000D_
    // starts the interval_x000D_
    $scope.start = function() {_x000D_
      // stops any running interval to avoid two intervals running at the same time_x000D_
      $scope.stop(); _x000D_
      _x000D_
      // store the interval promise_x000D_
      promise = $interval(setRandomizedCollection, 1000);_x000D_
    };_x000D_
  _x000D_
    // stops the interval_x000D_
    $scope.stop = function() {_x000D_
      $interval.cancel(promise);_x000D_
    };_x000D_
  _x000D_
    // starting the interval by default_x000D_
    $scope.start();_x000D_
 _x000D_
    // stops the interval when the scope is destroyed,_x000D_
    // this usually happens when a route is changed and _x000D_
    // the ItemsController $scope gets destroyed. The_x000D_
    // destruction of the ItemsController scope does not_x000D_
    // guarantee the stopping of any intervals, you must_x000D_
    // be responsible for stopping it when the scope is_x000D_
    // is destroyed._x000D_
    $scope.$on('$destroy', function() {_x000D_
      $scope.stop();_x000D_
    });_x000D_
            _x000D_
    function setRandomizedCollection() {_x000D_
      // items to randomize 1 - 11_x000D_
      var randomItems = parseInt(Math.random() * 10 + 1); _x000D_
        _x000D_
      // empties the items array_x000D_
      $scope.items.length = 0; _x000D_
      _x000D_
      // loop through random N times_x000D_
      while(randomItems--) {_x000D_
        _x000D_
        // push random number from 1 - 10000 to $scope.items_x000D_
        $scope.items.push(parseInt(Math.random() * 10000 + 1)); _x000D_
      }_x000D_
    }_x000D_
  _x000D_
  });
_x000D_
<div ng-app="app" ng-controller="ItemController">_x000D_
  _x000D_
  <!-- Event trigger to start the interval -->_x000D_
  <button type="button" ng-click="start()">Start Interval</button>_x000D_
  _x000D_
  <!-- Event trigger to stop the interval -->_x000D_
  <button type="button" ng-click="stop()">Stop Interval</button>_x000D_
  _x000D_
  <!-- display all the random items -->_x000D_
  <ul>_x000D_
    <li ng-repeat="item in items track by $index" ng-bind="item"></li>_x000D_
  </ul>_x000D_
  <!-- end of display -->_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
_x000D_
_x000D_
_x000D_

Using a Glyphicon as an LI bullet point (Bootstrap 3)

Using Font Awesome 5, the markup is a bit more complex than the previouis answer. Per the FA documentation, the markup should be:

<ul class="fa-ul">
  <li><span class="fa-li"><i class="fas fa-check-square"></i></span>List icons can</li>
  <li><span class="fa-li"><i class="fas fa-check-square"></i></span>be used to</li>
  <li><span class="fa-li"><i class="fas fa-spinner fa-pulse"></i></span>replace bullets</li>
  <li><span class="fa-li"><i class="far fa-square"></i></span>in lists</li>
</ul>

"Missing return statement" within if / for / while

If you put return statement in if, while or for statement then it may or may not return value. If it will not go inside these statement then also that method should return some value ( that could be null). To ensure that, compiler will force you to write this return statement which is after if, while or for.

But if you write if / else block and each one of them is having return in it then compiler knows that either if or else will get execute and method will return a value. So this time compiler will not force you.

if(condition)
{
 return;
}
else
{
 return;
}

Pointer to 2D arrays in C

//defines an array of 280 pointers (1120 or 2240 bytes)
int  *pointer1 [280];

//defines a pointer (4 or 8 bytes depending on 32/64 bits platform)
int (*pointer2)[280];      //pointer to an array of 280 integers
int (*pointer3)[100][280]; //pointer to an 2D array of 100*280 integers

Using pointer2 or pointer3 produce the same binary except manipulations as ++pointer2 as pointed out by WhozCraig.

I recommend using typedef (producing same binary code as above pointer3)

typedef int myType[100][280];
myType *pointer3;

Note: Since C++11, you can also use keyword using instead of typedef

using myType = int[100][280];
myType *pointer3;

in your example:

myType *pointer;                // pointer creation
pointer = &tab1;                // assignation
(*pointer)[5][12] = 517;        // set (write)
int myint = (*pointer)[5][12];  // get (read)

Note: If the array tab1 is used within a function body => this array will be placed within the call stack memory. But the stack size is limited. Using arrays bigger than the free memory stack produces a stack overflow crash.

The full snippet is online-compilable at gcc.godbolt.org

int main()
{
    //defines an array of 280 pointers (1120 or 2240 bytes)
    int  *pointer1 [280];
    static_assert( sizeof(pointer1) == 2240, "" );

    //defines a pointer (4 or 8 bytes depending on 32/64 bits platform)
    int (*pointer2)[280];      //pointer to an array of 280 integers
    int (*pointer3)[100][280]; //pointer to an 2D array of 100*280 integers  
    static_assert( sizeof(pointer2) == 8, "" );
    static_assert( sizeof(pointer3) == 8, "" );

    // Use 'typedef' (or 'using' if you use a modern C++ compiler)
    typedef int myType[100][280];
    //using myType = int[100][280];

    int tab1[100][280];

    myType *pointer;                // pointer creation
    pointer = &tab1;                // assignation
    (*pointer)[5][12] = 517;        // set (write)
    int myint = (*pointer)[5][12];  // get (read)

    return myint;
}

composer laravel create project

  1. Create project
  2. Open: Root (htdocs)\
  3. Press: Shift + Open command windows here
  4. Type: php composer.phar create-project --prefer-dist laravel/laravel lar-project "5.7.*"

How to output to the console and file?

I came up with this [untested]

import sys

class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)
            f.flush() # If you want the output to be visible immediately
    def flush(self) :
        for f in self.files:
            f.flush()

f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "test"  # This will go to stdout and the file out.txt

#use the original
sys.stdout = original
print "This won't appear on file"  # Only on stdout
f.close()

print>>xyz in python will expect a write() function in xyz. You could use your own custom object which has this. Or else, you could also have sys.stdout refer to your object, in which case it will be tee-ed even without >>xyz.

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.

Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.

However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.

org.apache.jasper.JasperException: Unable to compile class for JSP:

This line of yours:

<%@ page import="pageNumber.*, java.util.*, java.io.*" %>

Requires an @ symbol before % like this:

<%@ page import="pageNumber.*, java.util.*, java.io.*" @%>

How to detect a route change in Angular?

The cleaner way to do this would be to inherit RouteAware and implement the onNavigationEnd() method.

It's part of a library called @bespunky/angular-zen.

  1. npm install @bespunky/angular-zen

  2. Make your AppComponent extend RouteAware and add an onNavigationEnd() method.

import { Component     } from '@angular/core';
import { NavigationEnd } from '@angular/router';
import { RouteAware    } from '@bespunky/angular-zen/router-x';

@Component({
    selector   : 'app-root',
    templateUrl: './app.component.html',
    styleUrls  : ['./app.component.css']
})
export class AppComponent extends RouteAware
{    
    protected onNavigationEnd(event: NavigationEnd): void
    {
        // Handle authentication...
    }
}

RouteAware has other benefits such as:
? Any router event can have a handler method (Angular's supported router events).
? Use this.router to access the router
? Use this.route to access the activated route
? Use this.componentBus to access the RouterOutletComponentBus service

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

JAD Decomplier plug-in for Eclipse version 3.x and 4.x.

update site: http://feeling.sourceforge.net/update

Steps:

  1. Open Eclipse IDE.
  2. Click Help->Install New software
  3. Paste above URL and give name as JAD.
  4. Select the Eclipse Class Decompiler
  5. Click on Next and accept agreements
  6. Install it.
  7. Restart Eclipse and check now.

IF formula to compare a date with current date and return result

The formula provided by Blake doesn't seem to work for me. For past dates it returns due in xx days and for future dates, it returns overdue. Also, it will only return 15 days overdue, when it could actually be 30, 60 90+.

I created this, which seems to work and provides 'Due in xx days', 'Overdue xx days' and 'Due Today'.

=IF(ISBLANK(O10),"",IF(DAYS(TODAY(),O10)<0,CONCATENATE("Due in ",-DAYS(TODAY(),O10)," Days"),IF(DAYS(TODAY(),O10)>0,CONCATENATE("Overdue ",DAYS(TODAY(),O10)," Days"),"Due Today")))

AngularJS - convert dates in controller

All solutions here doesn't really bind the model to the input because you will have to change back the dateAsString to be saved as date in your object (in the controller after the form will be submitted).

If you don't need the binding effect, but just to show it in the input,

a simple could be:

<input type="date" value="{{ item.date | date: 'yyyy-MM-dd' }}" id="item_date" />

Then, if you like, in the controller, you can save the edited date in this way:

  $scope.item.date = new Date(document.getElementById('item_date').value).getTime();

be aware: in your controller, you have to declare your item variable as $scope.item in order for this to work.

Why can I not switch branches?

You need to commit or destroy any unsaved changes before you switch branch.

Git won't let you switch branch if it means unsaved changes would be removed.

How to create jobs in SQL Server Express edition

SQL Server Express editions are limited in some ways - one way is that they don't have the SQL Agent that allows you to schedule jobs.

There are a few third-party extensions that provide that capability - check out e.g.:

How to display PDF file in HTML?

I use Google Docs embeddable PDF viewer. The docs don't have to be uploaded to Google Docs, but they do have to be available online.

<iframe src="https://docs.google.com/gview?url=https://path.com/to/your/pdf.pdf&embedded=true" style="width:600px; height:500px;" frameborder="0"></iframe>

What is 'Context' on Android?

 Context means current. Context use to do operation for current screen. ex.
  1. getApplicationContext()
  2. getContext()

Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_SHORT).show();

Using Google Text-To-Speech in Javascript

Very easy with responsive voice. Just include the js and voila!

<script src='https://code.responsivevoice.org/responsivevoice.js'></script>

<input onclick="responsiveVoice.speak('This is the text you want to speak');" type='button' value=' Play' />

Get pandas.read_csv to read empty values as empty string instead of nan

We have a simple argument in Pandas read_csv for this:

Use:

df = pd.read_csv('test.csv', na_filter= False)

Pandas documentation clearly explains how the above argument works.

Link

How do I create and store md5 passwords in mysql

just get the hash by following line and store it into the database:

$encryptedValue = md5("YOUR STRING");

How To fix white screen on app Start up?

enter image description here

Like you tube.. initially they show icon screen instead of white screen. And after 2 seconds shows home screen.

first create an XML drawable in res/drawable.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/gray"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher"/>
    </item>

</layer-list>

Next, you will set this as your splash activity’s background in the theme. Navigate to your styles.xml file and add a new theme for your splash activity

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

    <style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@drawable/background_splash</item>
    </style>

</resources>

In your new SplashTheme, set the window background attribute to your XML drawable. Configure this as your splash activity’s theme in your AndroidManifest.xml:

<activity
    android:name=".SplashActivity"
    android:theme="@style/SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

This link gives what you want. step by step procedure. https://www.bignerdranch.com/blog/splash-screens-the-right-way/

UPDATE:

The layer-list can be even simpler like this (which also accepts vector drawables for the centered logo, unlike the <bitmap> tag):

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Background color -->
    <item android:drawable="@color/gray"/>

    <!-- Logo at the center of the screen -->
    <item
        android:drawable="@mipmap/ic_launcher"
        android:gravity="center"/>
</layer-list>

Running AMP (apache mysql php) on Android

I think this is what you're looking for: PAW Server from http://paw-android.fun2code.de/

hope it works

What is the difference between call and apply?

Difference between these to methods are, how you want to pass the parameters.

“A for array and C for comma” is a handy mnemonic.

jQuery CSS Opacity

try using .animate instead of .css or even just on the opacity one and leave .css on the display?? may b

jQuery(document).ready(function(){
if (jQuery('#nav .drop').animate('display') === 'block') {
    jQuery('#main').animate('opacity') = '0.6';

Fastest way to convert a dict's keys & values from `unicode` to `str`?

DATA = { u'spam': u'eggs', u'foo': frozenset([u'Gah!']), u'bar': { u'baz': 97 },
         u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])]}

def convert(data):
    if isinstance(data, basestring):
        return str(data)
    elif isinstance(data, collections.Mapping):
        return dict(map(convert, data.iteritems()))
    elif isinstance(data, collections.Iterable):
        return type(data)(map(convert, data))
    else:
        return data

print DATA
print convert(DATA)
# Prints:
# {u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])], u'foo': frozenset([u'Gah!']), u'bar': {u'baz': 97}, u'spam': u'eggs'}
# {'bar': {'baz': 97}, 'foo': frozenset(['Gah!']), 'list': ['list', (True, 'Maybe'), set(['and', 'a', 'set', 1])], 'spam': 'eggs'}

Assumptions:

  • You've imported the collections module and can make use of the abstract base classes it provides
  • You're happy to convert using the default encoding (use data.encode('utf-8') rather than str(data) if you need an explicit encoding).

If you need to support other container types, hopefully it's obvious how to follow the pattern and add cases for them.

JWT authentication for ASP.NET Web API

I answered this question: How to secure an ASP.NET Web API 4 years ago using HMAC.

Now, lots of things changed in security, especially that JWT is getting popular. In this answer, I will try to explain how to use JWT in the simplest and basic way that I can, so we won't get lost from jungle of OWIN, Oauth2, ASP.NET Identity... :)

If you don't know about JWT tokens, you need to take a look at:

https://tools.ietf.org/html/rfc7519

Basically, a JWT token looks like this:

<base64-encoded header>.<base64-encoded claims>.<base64-encoded signature>

Example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImN1b25nIiwibmJmIjoxNDc3NTY1NzI0LCJleHAiOjE0Nzc1NjY5MjQsImlhdCI6MTQ3NzU2NTcyNH0.6MzD1VwA5AcOcajkFyKhLYybr3h13iZjDyHm9zysDFQ

A JWT token has three sections:

  1. Header: JSON format which is encoded in Base64
  2. Claims: JSON format which is encoded in Base64.
  3. Signature: Created and signed based on Header and Claims which is encoded in Base64.

If you use the website jwt.io with the token above, you can decode the token and see it like below:

A screenshot of jwt.io with the raw jwt source and the decoded JSON it represents

Technically, JWT uses a signature which is signed from headers and claims with security algorithm specified in the headers (example: HMACSHA256). Therefore, JWT must be transferred over HTTPs if you store any sensitive information in its claims.

Now, in order to use JWT authentication, you don't really need an OWIN middleware if you have a legacy Web Api system. The simple concept is how to provide JWT token and how to validate the token when the request comes. That's it.

In the demo I've created (github), to keep the JWT token lightweight, I only store username and expiration time. But this way, you have to re-build new local identity (principal) to add more information like roles, if you want to do role authorization, etc. But, if you want to add more information into JWT, it's up to you: it's very flexible.

Instead of using OWIN middleware, you can simply provide a JWT token endpoint by using a controller action:

public class TokenController : ApiController
{
    // This is naive endpoint for demo, it should use Basic authentication
    // to provide token or POST request
    [AllowAnonymous]
    public string Get(string username, string password)
    {
        if (CheckUser(username, password))
        {
            return JwtManager.GenerateToken(username);
        }

        throw new HttpResponseException(HttpStatusCode.Unauthorized);
    }

    public bool CheckUser(string username, string password)
    {
        // should check in the database
        return true;
    }
}

This is a naive action; in production you should use a POST request or a Basic Authentication endpoint to provide the JWT token.

How to generate the token based on username?

You can use the NuGet package called System.IdentityModel.Tokens.Jwt from Microsoft to generate the token, or even another package if you like. In the demo, I use HMACSHA256 with SymmetricKey:

/// <summary>
/// Use the below code to generate symmetric Secret Key
///     var hmac = new HMACSHA256();
///     var key = Convert.ToBase64String(hmac.Key);
/// </summary>
private const string Secret = "db3OIsj+BXE9NZDy0t8W3TcNekrF+2d/1sFnWG4HnV8TZY30iTOdtVWJG8abWvB1GlOgJuQZdcF2Luqm/hccMw==";

public static string GenerateToken(string username, int expireMinutes = 20)
{
    var symmetricKey = Convert.FromBase64String(Secret);
    var tokenHandler = new JwtSecurityTokenHandler();

    var now = DateTime.UtcNow;
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.Name, username)
        }),

        Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),
        
        SigningCredentials = new SigningCredentials(
            new SymmetricSecurityKey(symmetricKey), 
            SecurityAlgorithms.HmacSha256Signature)
    };

    var stoken = tokenHandler.CreateToken(tokenDescriptor);
    var token = tokenHandler.WriteToken(stoken);

    return token;
}

The endpoint to provide the JWT token is done.

How to validate the JWT when the request comes?

In the demo, I have built JwtAuthenticationAttribute which inherits from IAuthenticationFilter (more detail about authentication filter in here).

With this attribute, you can authenticate any action: you just have to put this attribute on that action.

public class ValueController : ApiController
{
    [JwtAuthentication]
    public string Get()
    {
        return "value";
    }
}

You can also use OWIN middleware or DelegateHander if you want to validate all incoming requests for your WebAPI (not specific to Controller or action)

Below is the core method from authentication filter:

private static bool ValidateToken(string token, out string username)
{
    username = null;

    var simplePrinciple = JwtManager.GetPrincipal(token);
    var identity = simplePrinciple.Identity as ClaimsIdentity;

    if (identity == null)
        return false;

    if (!identity.IsAuthenticated)
        return false;

    var usernameClaim = identity.FindFirst(ClaimTypes.Name);
    username = usernameClaim?.Value;

    if (string.IsNullOrEmpty(username))
       return false;

    // More validate to check whether username exists in system

    return true;
}

protected Task<IPrincipal> AuthenticateJwtToken(string token)
{
    string username;

    if (ValidateToken(token, out username))
    {
        // based on username to get more information from database 
        // in order to build local identity
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, username)
            // Add more claims if needed: Roles, ...
        };

        var identity = new ClaimsIdentity(claims, "Jwt");
        IPrincipal user = new ClaimsPrincipal(identity);

        return Task.FromResult(user);
    }

    return Task.FromResult<IPrincipal>(null);
}

The workflow is to use the JWT library (NuGet package above) to validate the JWT token and then return back ClaimsPrincipal. You can perform more validation, like check whether user exists on your system, and add other custom validations if you want.

The code to validate JWT token and get principal back:

public static ClaimsPrincipal GetPrincipal(string token)
{
    try
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;

        if (jwtToken == null)
            return null;

        var symmetricKey = Convert.FromBase64String(Secret);

        var validationParameters = new TokenValidationParameters()
        {
            RequireExpirationTime = true,
            ValidateIssuer = false,
            ValidateAudience = false,
            IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
        };

        SecurityToken securityToken;
        var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);

        return principal;
    }
    catch (Exception)
    {
        //should write log
        return null;
    }
}

If the JWT token is validated and the principal is returned, you should build a new local identity and put more information into it to check role authorization.

Remember to add config.Filters.Add(new AuthorizeAttribute()); (default authorization) at global scope in order to prevent any anonymous request to your resources.

You can use Postman to test the demo:

Request token (naive as I mentioned above, just for demo):

GET http://localhost:{port}/api/token?username=cuong&password=1

Put JWT token in the header for authorized request, example:

GET http://localhost:{port}/api/value

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImN1b25nIiwibmJmIjoxNDc3NTY1MjU4LCJleHAiOjE0Nzc1NjY0NTgsImlhdCI6MTQ3NzU2NTI1OH0.dSwwufd4-gztkLpttZsZ1255oEzpWCJkayR_4yvNL1s

The demo can be found here: https://github.com/cuongle/WebApi.Jwt

Embed HTML5 YouTube video without iframe?

Yes, but it depends on what you mean by 'embed'; as far as I can tell after reading through the docs, it seems like you have a couple of options if you want to get around using the iframe API. You can use the javascript and flash API's (https://developers.google.com/youtube/player_parameters) to embed a player, but that involves creating Flash objects in your code (something I personally avoid, but not necessarily something that you have to). Below are some helpful sections from the dev docs for the Youtube API.

If you really want to get around all these methods and include video without any sort of iframe, then your best bet might be creating an HTML5 video player/app that can connect to the Youtube Data API (https://developers.google.com/youtube/v3/). I'm not sure what the extent of your needs are, but this would be the way to go if you really want to get around using any iframes or flash objects.

Hope this helps!


Useful:

(https://developers.google.com/youtube/player_parameters)

IFrame embeds using the IFrame Player API

Follow the IFrame Player API instructions to insert a video player in your web page or application after the Player API's JavaScript code has loaded. The second parameter in the constructor for the video player is an object that specifies player options. Within that object, the playerVars property identifies player parameters.

The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.

...

IFrame embeds using tags

Define an tag in your application in which the src URL specifies the content that the player will load as well as any other player parameters you want to set. The tag's height and width parameters specify the dimensions of the player.

If you are creating the element yourself (rather than using the IFrame Player API to create it), you can append player parameters directly to the end of the URL. The URL has the following format:

...

AS3 object embeds

Object embeds use an tag to specify the player's dimensions and parameters. The sample code below demonstrates how to use an object embed to load an AS3 player that automatically plays the same video as the previous two examples.

Equivalent of Clean & build in Android Studio?

It is probably not a correct way for clean, but I made that to delete unnecessary files, and take less size of a project. It continuously finds and deletes all build and Gradle folders made file clean.bat copy that into the folder where your project is

  set mypath=%cd% 
    for /d /r %mypath% %%a in (build\) do if exist "%%a" rmdir /s /q "%%a"
    for /d /r %mypath% %%a in (.gradle\) do if exist "%%a" rmdir /s /q "%%a"

Java's L number (long) specification

To understand why it is necessary to distinguish between int and long literals, consider:

long l = -1 >>> 1;

versus

int a = -1;
long l = a >>> 1;

Now as you would rightly expect, both code fragments give the same value to variable l. Without being able to distinguish int and long literals, what is the interpretation of -1 >>> 1?

-1L >>> 1 // ?

or

(int)-1 >>> 1 // ?

So even if the number is in the common range, we need to specify type. If the default changed with magnitude of the literal, then there would be a weird change in the interpretations of expressions just from changing the digits.

This does not occur for byte, short and char because they are always promoted before performing arithmetic and bitwise operations. Arguably their should be integer type suffixes for use in, say, array initialisation expressions, but there isn't. float uses suffix f and double d. Other literals have unambiguous types, with there being a special type for null.

How to Rotate a UIImage 90 degrees?

I believe the easiest way (and thread safe too) is to do:

//assume that the image is loaded in landscape mode from disk
UIImage * landscapeImage = [UIImage imageNamed:imgname];
UIImage * portraitImage = [[UIImage alloc] initWithCGImage: landscapeImage.CGImage
                                                     scale: 1.0
                                               orientation: UIImageOrientationRight];

Note: As Brainware said this only modifies the orientation data of the image - the pixel data is untouched. For some applications, this may not be enough.

Or in Swift:

guard
    let landscapeImage = UIImage(named: "imgname"),
    let landscapeCGImage = landscapeImage.cgImage
else { return }
let portraitImage = UIImage(cgImage: landscapeCGImage, scale: landscapeImage.scale, orientation: .right)

How to make a page redirect using JavaScript?

You can call a JavaScript function and use window.location = 'url';:

http://www.pageresource.com/jscript/jredir.htm

How to grep recursively, but only in files with certain extensions?

How about:

find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Place your script inside the body tag

<body>
  // Rest of html
  <script>
  function hideButton() {
    $(".loading").hide();
  }
function showButton() {
  $(".loading").show();
}
</script> 
< /body>

If you check this JSFIDDLE and click on javascript, you will see the load Type body is selected

How to change font-color for disabled input?

input[disabled], input[disabled]:hover { background-color:#444; }

How do I get the height and width of the Android Navigation Bar programmatically?

The height of the bottom Navigation bar is 48dp (in both portrait and landscape mode) and is 42dp when the bar is placed vertically.

.htaccess or .htpasswd equivalent on IIS?

I've never used it but Trilead, a free ISAPI filter which enables .htaccess based control, looks like what you want.

Count characters in textarea

$(document).ready(function() {
    var count = $("h1").text().length;
    alert(count);
});

Also, you can put your own element id or class instead of "h1" and length event count your characters of text area string ?

prevent iphone default keyboard when focusing an <input>

So here is my solution (similar to John Vance's answer):

First go here and get a function to detect mobile browsers.

http://detectmobilebrowsers.com/

They have a lot of different ways to detect if you are on mobile, so find one that works with what you are using.

Your HTML page (pseudo code):

If Mobile Then
    <input id="selling-date" type="date" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />
else
    <input id="selling-date" type="text" class="date-picker" readonly="readonly" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />

JQuery:

$( ".date-picker" ).each(function() {
    var min = $( this ).attr("min");
    var max = $( this ).attr("max");
    $( this ).datepicker({ 
        dateFormat: "yy-mm-dd",  
        minDate: min,  
        maxDate: max  
    });
});

This way you can still use native date selectors in mobile while still setting the min and max dates either way.

The field for non mobile should be read only because if a mobile browser like chrome for ios "requests desktop version" then they can get around the mobile check and you still want to prevent the keyboard from showing up.

However if the field is read only it could look to a user like they cant change the field. You could fix this by changing the CSS to make it look like it isn't read only (ie change border-color to black) but unless you are changing the CSS for all input tags you will find it hard to keep the look consistent across browsers.

To get arround that I just add a calendar image button to the date picker. Just change your JQuery code a bit:

$( ".date-picker" ).each(function() {
    var min = $( this ).attr("min");
    var max = $( this ).attr("max");
    $( this ).datepicker({ 
        dateFormat: "yy-mm-dd",  
        minDate: min,  
        maxDate: max,
        showOn: "both",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        buttonText: "Select date"
    });
});

Note: you will have to find a suitable image.

How to remove \n from a list element?

This works to take out the \n (new line) off a item in a list it just takes the first item in string off

def remove_end(s):
    templist=[]
    for i in s:
        templist.append(i)
    return(templist[0])

SQL how to increase or decrease one for a int column in one command

to answer the second:

make the column unique and catch the exception if it's set to the same value.

List of IP addresses/hostnames from local network in Python

Here is a small tool scanip that will help you to get all ip addresses and their corresponding mac addresses in the network (Works on Linux).

https://github.com/vivkv/scanip

Web scraping with Java

You might look into jwht-scrapper!

This is a complete scrapping framework that has all the features a developper could expect from a web scrapper:

It works with (jwht-htmltopojo)[https://github.com/whimtrip/jwht-htmltopojo) lib which itsef uses Jsoup mentionned by several other people here.

Together they will help you built awesome scrappers mapping directly HTML to POJOs and bypassing any classical scrapping problems in only a matter of minutes!

Hope this might help some people here!

Disclaimer, I am the one who developed it, feel free to let me know your remarks!

Converting a Uniform Distribution to a Normal Distribution

The standard Python library module random has what you want:

normalvariate(mu, sigma)
Normal distribution. mu is the mean, and sigma is the standard deviation.

For the algorithm itself, take a look at the function in random.py in the Python library.

The manual entry is here

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.

In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.

List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : multiparts) {
        if (!item.isFormField()) {
            //your operations on file
        } else {
            String name = item.getFieldName();
            String value = item.getString();
            //you operations on paramters
        }
}

How to center a window on the screen in Tkinter?

This method is cross-platform, works for multiple monitors/screens (targets the active screen), and requires no other libraries than Tk. The root window will appear centered without any unwanted "flashing" or animations:

import tkinter as tk

def get_geometry(frame):
    geometry = frame.winfo_geometry()
    match = re.match(r'^(\d+)x(\d+)\+(\d+)\+(\d+)$', geometry)
    return [int(val) for val in match.group(*range(1, 5))]

def center_window(root):
    """Must be called after application is fully initialized
    so that the root window is the true final size."""
    # Avoid unwanted "flashing" by making window transparent until fully ready
    root.attributes('-alpha', 0)

    # Get dimensions of active screen/monitor using fullscreen trick; withdraw
    # window before making it fullscreen to preserve previous dimensions
    root.withdraw()
    root.attributes('-fullscreen', True)
    root.update_idletasks()
    (screen_width, screen_height, *_) = get_geometry(root)
    root.attributes('-fullscreen', False)

    # Restore and get "natural" window dimensions
    root.deiconify()
    root.update_idletasks()
    (window_width, window_height, *_) = get_geometry(root)

    # Compute and set proper window center
    pos_x = round(screen_width / 2 - window_width / 2)
    pos_y = round(screen_height / 2 - window_height / 2)
    root.geometry(f'+{pos_x}+{pos_y}')
    root.update_idletasks()
    
    root.attributes('-alpha', 1)

# Usage:
root = tk.Tk()
center_window(root)

Note that at every point where window geometry is modified, update_idletasks() must be called to force the operation to occur synchronously/immediately. It uses Python 3 functionality but can easily be adapted to Python 2.x if necessary.

Referenced Project gets "lost" at Compile Time

Check your build types of each project under project properties - I bet one or the other will be set to build against .NET XX - Client Profile.

With inconsistent versions, specifically with one being Client Profile and the other not, then it works at design time but fails at compile time. A real gotcha.

There is something funny going on in Visual Studio 2010 for me, which keeps setting projects seemingly randomly to Client Profile, sometimes when I create a project, and sometimes a few days later. Probably some keyboard shortcut I'm accidentally hitting...

How to iterate through XML in Powershell?

You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)

$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property

Or just this, xpath is case sensitive. Both have the same output:

$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml


Name         Type                                                #text
----         ----                                                -----
DisplayName  System.String                                       SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName  System.String                                       SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.

jquery save json data object in cookie

It is not good practice to save the value that is returned from JSON.stringify(userData) to a cookie; it can lead to a bug in some browsers.

Before using it, you should convert it to base64 (using btoa), and when reading it, convert from base64 (using atob).

val = JSON.stringify(userData)
val = btoa(val)

write_cookie(val)

SVN: Is there a way to mark a file as "do not commit"?

I came to this thread looking for a way to make an "atomic" commit of just some files and instead of ignoring some files on commit I went the other way and only commited the files I wanted:

svn ci filename1 filename2

Maybe, it will help someone.

WPF: Grid with column/row margin/padding?

I had similar problem recently in two column grid, I needed a margin on elements in right column only. All elements in both columns were of type TextBlock.

<Grid.Resources>
    <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource OurLabelStyle}">
        <Style.Triggers>
            <Trigger Property="Grid.Column" Value="1">
                <Setter Property="Margin" Value="20,0" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Grid.Resources>

Enum "Inheritance"

This is what I did. What I've done differently is use the same name and the new keyword on the "consuming" enum. Since the name of the enum is the same, you can just mindlessly use it and it will be right. Plus you get intellisense. You just have to manually take care when setting it up that the values are copied over from the base and keep them sync'ed. You can help that along with code comments. This is another reason why in the database when storing enum values I always store the string, not the value. Because if you are using automatically assigned increasing integer values those can change over time.

// Base Class for balls 
public class BaseBall
{
    // keep synced with subclasses!
    public enum Sizes
    {
        Small,
        Medium,
        Large
    }
}

public class VolleyBall : BaseBall
{
    // keep synced with base class!
    public new enum Sizes
    {
        Small = BaseBall.Sizes.Small,
        Medium = BaseBall.Sizes.Medium,
        Large = BaseBall.Sizes.Large,
        SmallMedium,
        MediumLarge,
        Ginormous
    }
}

Display filename before matching line

Try this little trick to coax grep into thinking it is dealing with multiple files, so that it displays the filename:

grep 'pattern' file /dev/null

To also get the line number:

grep -n 'pattern' file /dev/null

How to reload current page in ReactJS?

This is my code .This works for me

componentDidMount(){
        axios.get('http://localhost:5000/supplier').then(
            response => {
                console.log(response)
                this.setState({suppliers:response.data.data})
            }
        )
        .catch(error => {
            console.log(error)
        })
        
    }

componentDidUpdate(){
        this.componentDidMount();
}

window.location.reload(); I think this thing is not good for react js

Where should my npm modules be installed on Mac OS X?

/usr/local/lib/node_modules is the correct directory for globally installed node modules.

/usr/local/share/npm/lib/node_modules makes no sense to me. One issue here is that you're confused because there are two directories called node_modules:

/usr/local/lib/node_modules
/usr/local/lib/node_modules/npm/node_modules

The latter seems to be node modules that came with Node, e.g., lodash, when the former is Node modules that I installed using npm.

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

Issue is with the Json.parse of empty array - scatterSeries , as you doing console log of scatterSeries before pushing ch

_x000D_
_x000D_
var data = { "results":[  _x000D_
  [  _x000D_
     {  _x000D_
        "b":"0.110547334",_x000D_
        "cost":"0.000000",_x000D_
        "w":"1.998889"_x000D_
     }_x000D_
  ],_x000D_
  [  _x000D_
     {  _x000D_
        "x":0,_x000D_
        "y":0_x000D_
     },_x000D_
     {  _x000D_
        "x":1,_x000D_
        "y":2_x000D_
     },_x000D_
     {  _x000D_
        "x":2,_x000D_
        "y":4_x000D_
     },_x000D_
     {  _x000D_
        "x":3,_x000D_
        "y":6_x000D_
     },_x000D_
     {  _x000D_
        "x":4,_x000D_
        "y":8_x000D_
     },_x000D_
     {  _x000D_
        "x":5,_x000D_
        "y":10_x000D_
     },_x000D_
     {  _x000D_
        "x":6,_x000D_
        "y":12_x000D_
     },_x000D_
     {  _x000D_
        "x":7,_x000D_
        "y":14_x000D_
     },_x000D_
     {  _x000D_
        "x":8,_x000D_
        "y":16_x000D_
     },_x000D_
     {  _x000D_
        "x":9,_x000D_
        "y":18_x000D_
     },_x000D_
     {  _x000D_
        "x":10,_x000D_
        "y":20_x000D_
     },_x000D_
     {  _x000D_
        "x":11,_x000D_
        "y":22_x000D_
     },_x000D_
     {  _x000D_
        "x":12,_x000D_
        "y":24_x000D_
     },_x000D_
     {  _x000D_
        "x":13,_x000D_
        "y":26_x000D_
     },_x000D_
     {  _x000D_
        "x":14,_x000D_
        "y":28_x000D_
     },_x000D_
     {  _x000D_
        "x":15,_x000D_
        "y":30_x000D_
     },_x000D_
     {  _x000D_
        "x":16,_x000D_
        "y":32_x000D_
     },_x000D_
     {  _x000D_
        "x":17,_x000D_
        "y":34_x000D_
     },_x000D_
     {  _x000D_
        "x":18,_x000D_
        "y":36_x000D_
     },_x000D_
     {  _x000D_
        "x":19,_x000D_
        "y":38_x000D_
     },_x000D_
     {  _x000D_
        "x":20,_x000D_
        "y":40_x000D_
     },_x000D_
     {  _x000D_
        "x":21,_x000D_
        "y":42_x000D_
     },_x000D_
     {  _x000D_
        "x":22,_x000D_
        "y":44_x000D_
     },_x000D_
     {  _x000D_
        "x":23,_x000D_
        "y":46_x000D_
     },_x000D_
     {  _x000D_
        "x":24,_x000D_
        "y":48_x000D_
     },_x000D_
     {  _x000D_
        "x":25,_x000D_
        "y":50_x000D_
     },_x000D_
     {  _x000D_
        "x":26,_x000D_
        "y":52_x000D_
     },_x000D_
     {  _x000D_
        "x":27,_x000D_
        "y":54_x000D_
     },_x000D_
     {  _x000D_
        "x":28,_x000D_
        "y":56_x000D_
     },_x000D_
     {  _x000D_
        "x":29,_x000D_
        "y":58_x000D_
     },_x000D_
     {  _x000D_
        "x":30,_x000D_
        "y":60_x000D_
     },_x000D_
     {  _x000D_
        "x":31,_x000D_
        "y":62_x000D_
     },_x000D_
     {  _x000D_
        "x":32,_x000D_
        "y":64_x000D_
     },_x000D_
     {  _x000D_
        "x":33,_x000D_
        "y":66_x000D_
     },_x000D_
     {  _x000D_
        "x":34,_x000D_
        "y":68_x000D_
     },_x000D_
     {  _x000D_
        "x":35,_x000D_
        "y":70_x000D_
     },_x000D_
     {  _x000D_
        "x":36,_x000D_
        "y":72_x000D_
     },_x000D_
     {  _x000D_
        "x":37,_x000D_
        "y":74_x000D_
     },_x000D_
     {  _x000D_
        "x":38,_x000D_
        "y":76_x000D_
     },_x000D_
     {  _x000D_
        "x":39,_x000D_
        "y":78_x000D_
     },_x000D_
     {  _x000D_
        "x":40,_x000D_
        "y":80_x000D_
     },_x000D_
     {  _x000D_
        "x":41,_x000D_
        "y":82_x000D_
     },_x000D_
     {  _x000D_
        "x":42,_x000D_
        "y":84_x000D_
     },_x000D_
     {  _x000D_
        "x":43,_x000D_
        "y":86_x000D_
     },_x000D_
     {  _x000D_
        "x":44,_x000D_
        "y":88_x000D_
     },_x000D_
     {  _x000D_
        "x":45,_x000D_
        "y":90_x000D_
     },_x000D_
     {  _x000D_
        "x":46,_x000D_
        "y":92_x000D_
     },_x000D_
     {  _x000D_
        "x":47,_x000D_
        "y":94_x000D_
     },_x000D_
     {  _x000D_
        "x":48,_x000D_
        "y":96_x000D_
     },_x000D_
     {  _x000D_
        "x":49,_x000D_
        "y":98_x000D_
     },_x000D_
     {  _x000D_
        "x":50,_x000D_
        "y":100_x000D_
     },_x000D_
     {  _x000D_
        "x":51,_x000D_
        "y":102_x000D_
     },_x000D_
     {  _x000D_
        "x":52,_x000D_
        "y":104_x000D_
     },_x000D_
     {  _x000D_
        "x":53,_x000D_
        "y":106_x000D_
     },_x000D_
     {  _x000D_
        "x":54,_x000D_
        "y":108_x000D_
     },_x000D_
     {  _x000D_
        "x":55,_x000D_
        "y":110_x000D_
     },_x000D_
     {  _x000D_
        "x":56,_x000D_
        "y":112_x000D_
     },_x000D_
     {  _x000D_
        "x":57,_x000D_
        "y":114_x000D_
     },_x000D_
     {  _x000D_
        "x":58,_x000D_
        "y":116_x000D_
     },_x000D_
     {  _x000D_
        "x":59,_x000D_
        "y":118_x000D_
     },_x000D_
     {  _x000D_
        "x":60,_x000D_
        "y":120_x000D_
     },_x000D_
     {  _x000D_
        "x":61,_x000D_
        "y":122_x000D_
     },_x000D_
     {  _x000D_
        "x":62,_x000D_
        "y":124_x000D_
     },_x000D_
     {  _x000D_
        "x":63,_x000D_
        "y":126_x000D_
     },_x000D_
     {  _x000D_
        "x":64,_x000D_
        "y":128_x000D_
     },_x000D_
     {  _x000D_
        "x":65,_x000D_
        "y":130_x000D_
     },_x000D_
     {  _x000D_
        "x":66,_x000D_
        "y":132_x000D_
     },_x000D_
     {  _x000D_
        "x":67,_x000D_
        "y":134_x000D_
     },_x000D_
     {  _x000D_
        "x":68,_x000D_
        "y":136_x000D_
     },_x000D_
     {  _x000D_
        "x":69,_x000D_
        "y":138_x000D_
     },_x000D_
     {  _x000D_
        "x":70,_x000D_
        "y":140_x000D_
     },_x000D_
     {  _x000D_
        "x":71,_x000D_
        "y":142_x000D_
     },_x000D_
     {  _x000D_
        "x":72,_x000D_
        "y":144_x000D_
     },_x000D_
     {  _x000D_
        "x":73,_x000D_
        "y":146_x000D_
     },_x000D_
     {  _x000D_
        "x":74,_x000D_
        "y":148_x000D_
     },_x000D_
     {  _x000D_
        "x":75,_x000D_
        "y":150_x000D_
     },_x000D_
     {  _x000D_
        "x":76,_x000D_
        "y":152_x000D_
     },_x000D_
     {  _x000D_
        "x":77,_x000D_
        "y":154_x000D_
     },_x000D_
     {  _x000D_
        "x":78,_x000D_
        "y":156_x000D_
     },_x000D_
     {  _x000D_
        "x":79,_x000D_
        "y":158_x000D_
     },_x000D_
     {  _x000D_
        "x":80,_x000D_
        "y":160_x000D_
     },_x000D_
     {  _x000D_
        "x":81,_x000D_
        "y":162_x000D_
     },_x000D_
     {  _x000D_
        "x":82,_x000D_
        "y":164_x000D_
     },_x000D_
     {  _x000D_
        "x":83,_x000D_
        "y":166_x000D_
     },_x000D_
     {  _x000D_
        "x":84,_x000D_
        "y":168_x000D_
     },_x000D_
     {  _x000D_
        "x":85,_x000D_
        "y":170_x000D_
     },_x000D_
     {  _x000D_
        "x":86,_x000D_
        "y":172_x000D_
     },_x000D_
     {  _x000D_
        "x":87,_x000D_
        "y":174_x000D_
     },_x000D_
     {  _x000D_
        "x":88,_x000D_
        "y":176_x000D_
     },_x000D_
     {  _x000D_
        "x":89,_x000D_
        "y":178_x000D_
     },_x000D_
     {  _x000D_
        "x":90,_x000D_
        "y":180_x000D_
     },_x000D_
     {  _x000D_
        "x":91,_x000D_
        "y":182_x000D_
     },_x000D_
     {  _x000D_
        "x":92,_x000D_
        "y":184_x000D_
     },_x000D_
     {  _x000D_
        "x":93,_x000D_
        "y":186_x000D_
     },_x000D_
     {  _x000D_
        "x":94,_x000D_
        "y":188_x000D_
     },_x000D_
     {  _x000D_
        "x":95,_x000D_
        "y":190_x000D_
     },_x000D_
     {  _x000D_
        "x":96,_x000D_
        "y":192_x000D_
     },_x000D_
     {  _x000D_
        "x":97,_x000D_
        "y":194_x000D_
     },_x000D_
     {  _x000D_
        "x":98,_x000D_
        "y":196_x000D_
     },_x000D_
     {  _x000D_
        "x":99,_x000D_
        "y":198_x000D_
     }_x000D_
  ]]};_x000D_
_x000D_
var scatterSeries = []; _x000D_
_x000D_
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';_x000D_
               console.info(ch);_x000D_
               _x000D_
               scatterSeries.push(JSON.parse(ch));_x000D_
console.info(scatterSeries);
_x000D_
_x000D_
_x000D_

code sample - https://codepen.io/nagasai/pen/GGzZVB

fill an array in C#

Write yourself an extension method

public static class ArrayExtensions {
    public static void Fill<T>(this T[] originalArray, T with) {
        for(int i = 0; i < originalArray.Length; i++){
            originalArray[i] = with;
        }
    }  
}

and use it like

int foo[] = new int[]{0,0,0,0,0};
foo.Fill(13);

will fill all the elements with 13

PostgreSQL DISTINCT ON with different ORDER BY

Documentation says:

DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. [...] Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. [...] The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s).

Official documentation

So you'll have to add the address_id to the order by.

Alternatively, if you're looking for the full row that contains the most recent purchased product for each address_id and that result sorted by purchased_at then you're trying to solve a greatest N per group problem which can be solved by the following approaches:

The general solution that should work in most DBMSs:

SELECT t1.* FROM purchases t1
JOIN (
    SELECT address_id, max(purchased_at) max_purchased_at
    FROM purchases
    WHERE product_id = 1
    GROUP BY address_id
) t2
ON t1.address_id = t2.address_id AND t1.purchased_at = t2.max_purchased_at
ORDER BY t1.purchased_at DESC

A more PostgreSQL-oriented solution based on @hkf's answer:

SELECT * FROM (
  SELECT DISTINCT ON (address_id) *
  FROM purchases 
  WHERE product_id = 1
  ORDER BY address_id, purchased_at DESC
) t
ORDER BY purchased_at DESC

Problem clarified, extended and solved here: Selecting rows ordered by some column and distinct on another

sorting a vector of structs

As others have mentioned, you could use a comparison function, but you can also overload the < operator and the default less<T> functor will work as well:

struct data {
    string word;
    int number;
    bool operator < (const data& rhs) const {
        return word.size() < rhs.word.size();
    }
};

Then it's just:

std::sort(info.begin(), info.end());

Edit

As James McNellis pointed out, sort does not actually use the less<T> functor by default. However, the rest of the statement that the less<T> functor will work as well is still correct, which means that if you wanted to put struct datas into a std::map or std::set this would still work, but the other answers which provide a comparison function would need additional code to work with either.

must appear in the GROUP BY clause or be used in an aggregate function

For me, it is not about a "common aggregation problem", but just about an incorrect SQL query. The single correct answer for "select the maximum avg for each cname..." is

SELECT cname, MAX(avg) FROM makerar GROUP BY cname;

The result will be:

 cname  |      MAX(avg)
--------+---------------------
 canada | 2.0000000000000000
 spain  | 5.0000000000000000

This result in general answers the question "What is the best result for each group?". We see that the best result for spain is 5 and for canada the best result is 2. It is true, and there is no error. If we need to display wmname also, we have to answer the question: "What is the RULE to choose wmname from resulting set?" Let's change the input data a bit to clarify the mistake:

  cname | wmname |        avg           
--------+--------+-----------------------
 spain  | zoro   |  1.0000000000000000
 spain  | luffy  |  5.0000000000000000
 spain  | usopp  |  5.0000000000000000

Which result do you expect on runnig this query: SELECT cname, wmname, MAX(avg) FROM makerar GROUP BY cname;? Should it be spain+luffy or spain+usopp? Why? It is not determined in the query how to choose "better" wmname if several are suitable, so the result is also not determined. That's why SQL interpreter returns an error - the query is not correct.

In the other word, there is no correct answer to the question "Who is the best in spain group?". Luffy is not better than usopp, because usopp has the same "score".

How to select data from 30 days?

For those who could not get DATEADD to work, try this instead: ( NOW( ) - INTERVAL 1 MONTH )

How to set UTF-8 encoding for a PHP file

Also note that setting a header to "text/plain" will result in all html and php (in part) printing the characters on the screen as TEXT, not as HTML. So be aware of possible HTML not parsing when using text type plain.

Using:

header('Content-type: text/html; charset=utf-8');

Can return HTML and PHP as well. Not just text.

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

http://www.eclipse.org/cdt/ ^Give that a try

I have not used the CDT for eclipse but I do use Eclipse Java for Ubuntu 12.04 and it works wonders.

Android emulator doesn't take keyboard input - SDK tools rev 20

In your home folder /.android/avd//config.ini add the line hw.keyboard=yes

Environment variable in Jenkins Pipeline

You can access the same environment variables from groovy using the same names (e.g. JOB_NAME or env.JOB_NAME).

From the documentation:

Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):

env.MYTOOL_VERSION = '1.33'
node {
  sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
}

These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.

For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job enter image description here

ignoring any 'bin' directory on a git project

[Bb]in/

matches both upper and lower case

List of All Folders and Sub-folders

As well as find listed in other answers, better shells allow both recurvsive globs and filtering of glob matches, so in zsh for example...

ls -lad **/*(/)

...lists all directories while keeping all the "-l" details that you want, which you'd otherwise need to recreate using something like...

find . -type d -exec ls -ld {} \;

(not quite as easy as the other answers suggest)

The benefit of find is that it's more independent of the shell - more portable, even for system() calls from within a C/C++ program etc..

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Here is how to do a quick check to see if n.fn.init[0] is caused by your DOM-elements not loading in time. Delay your selector function by wrapping it in setTimeout function like this:

function timeout(){ 

    ...your selector function that returns n.fn.init[0] goes here...

}

setTimeout(timeout, 5000)

This will cause your selector function to execute with a 5 second delay, which should be enough for pretty much anything to load.

This is just a coarse hack to check if DOM is ready for your selector function or not. This is not a (permanent) solution.

The preferred ways to check if the DOM is loaded before executing your function are as follows:

1) Wrap your selector function in

$(document).ready(function(){  ... your selector function...  };

2) If that doesn't work, use DOMContentLoaded

3) Try window.onload, which waits for all the images to load first, so its least preferred

window.onload = function () {  ... your selector function...  }

4) If you are waiting for a library to load that loads in several steps or has some sort of delay of its own, then you might need some complicated custom solution. This is what happened to me with "MathJax" library. This question discusses how to check when MathJax library loaded its DOM elements, if it is of any help.

5) Finally, you can stick with hard-coded setTimeout function, making it maybe 1-3 seconds. This is actually the very least preferred method in my opinion.

This list of fixes is probably far from perfect so everyone is welcome to edit it.

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

Count the number of commits on a Git branch

It might require a relatively recent version of Git, but this works well for me:

git rev-list --count develop..HEAD

This gives me an exact count of commits in the current branch having its base on master.

The command in Peter's answer, git rev-list --count HEAD ^develop includes many more commits, 678 vs 97 on my current project.

My commit history is linear on this branch, so YMMV, but it gives me the exact answer I wanted, which is "How many commits have I added so far on this feature branch?".

Convert string to a variable name

Use x=as.name("string"). You can use then use x to refer to the variable with name string.

I don't know, if it answers your question correctly.

Jersey stopped working with InjectionManagerFactory not found

Choose which DI to inject stuff into Jersey:

Spring 4:

<dependency>
  <groupId>org.glassfish.jersey.ext</groupId>
  <artifactId>jersey-spring4</artifactId>
</dependency>

Spring 3:

<dependency>
  <groupId>org.glassfish.jersey.ext</groupId>
  <artifactId>jersey-spring3</artifactId>
</dependency>

HK2:

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
</dependency>

Generate a UUID on iOS from Swift

You could also just use the NSUUID API:

let uuid = NSUUID()

If you want to get the string value back out, you can use uuid.UUIDString.

Note that NSUUID is available from iOS 6 and up.

How to generate XML from an Excel VBA macro?

Here is the example macro to convert the Excel worksheet to XML file.

#'vba code to convert excel to xml

Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
        xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False

End Sub

This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.

SQL SELECT from multiple tables

SELECT `product`.*, `customer1`.`name1`, `customer2`.`name2`
FROM `product`
LEFT JOIN `customer1` ON `product`.`cid` = `customer1`.`cid`
LEFT JOIN `customer2` ON `product`.`cid` = `customer2`.`cid`

Concatenating date with a string in Excel

You can do it this simple way :

A1 = Mahi
A2 = NULL(blank)

Select A2 Right click on cell --> Format cells --> change to TEXT

Then put the date in A2 (A2 =31/07/1990)

Then concatenate it will work. No need of any formulae.

=CONCATENATE(A1,A2)

mahi31/07/1990

(This works on the empty cells ie.,Before entering the DATE value to cell you need to make it as TEXT).

Restrict SQL Server Login access to only one database

this is to topup to what was selected as the correct answer. It has one missing step that when not done, the user will still be able to access the rest of the database. First, do as @DineshDB suggested

  1. Connect to your SQL server instance using management studio
   2. Goto Security -> Logins -> (RIGHT CLICK) New Login
   3. fill in user details
   4. Under User Mapping, select the databases you want the user to be able to access and configure

the missing step is below:

5. Under user mapping, ensure that "sysadmin" is NOT CHECKED and select "db_owner" as the role for the new user.

And thats it.

Remove json element

As described by @mplungjan, I though it was right. Then right away I click the up rate button. But by following it, I finally got an error.

<script>
var data = {"result":[
  {"FirstName":"Test1","LastName":"User","Email":"[email protected]","City":"ahmedabad","State":"sk","Country":"canada","Status":"False","iUserID":"23"},
  {"FirstName":"user","LastName":"user","Email":"[email protected]","City":"ahmedabad","State":"Gujarat","Country":"India","Status":"True","iUserID":"41"},
  {"FirstName":"Ropbert","LastName":"Jones","Email":"[email protected]","City":"NewYork","State":"gfg","Country":"fgdfgdfg","Status":"True","iUserID":"48"},
  {"FirstName":"hitesh","LastName":"prajapti","Email":"[email protected]","City":"","State":"","Country":"","Status":"True","iUserID":"78"}
  ]
}
alert(data.result)
delete data.result[3]
alert(data.result)
</script>

Delete is just remove the data, but the 'place' is still there as undefined.

I did this and it works like a charm :

data.result.splice(2,1);  

meaning : delete 1 item at position 3 ( because array is counted form 0, then item at no 3 is counted as no 2 )

Difference between angle bracket < > and double quotes " " while including header files in C++?

It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2):

A preprocessing directive of the form

  # include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

  # include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

  # include <h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original directive.

So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.

SQL - HAVING vs. WHERE

You can not use where clause with aggregate functions because where fetch records on the basis of condition, it goes into table record by record and then fetch record on the basis of condition we have give. So that time we can not where clause. While having clause works on the resultSet which we finally get after running a query.

Example query:

select empName, sum(Bonus) 
from employees 
order by empName 
having sum(Bonus) > 5000;

This will store the resultSet in a temporary memory, then having clause will perform its work. So we can easily use aggregate functions here.

Where is SQL Profiler in my SQL Server 2008?

Management Studio->Tools->SQL Server Profiler.

If it is not installed see this link

Vue.js toggle class on click

This example is using Lists: When clicking in some li it turn red

html:

<div id="app">
  <ul>
    <li @click="activate(li.id)" :class="{ active : active_el == li.id }" v-for="li in lista">{{li.texto}}</li>   
  </ul>
</div>

JS:

var app = new Vue({
  el:"#app",
  data:{
    lista:[{"id":"1","texto":"line 1"},{"id":"2","texto":"line 2"},{"id":"3","texto":"line 3"},{"id":"4","texto":"line 4"},{"id":"5","texto":"line 5"}],
    active_el:0
  },
  methods:{
    activate:function(el){
        this.active_el = el;
    }
  }
});

css

ul > li:hover {
  cursor:pointer;
}
.active {
  color:red;
  font-weight:bold;
}

Fiddle:

https://jsfiddle.net/w37vLL68/158/

RegEx to parse or validate Base64 data

Neither a ":" nor a "." will show up in valid Base64, so I think you can unambiguously throw away the http://www.stackoverflow.com line. In Perl, say, something like

my $sanitized_str = join q{}, grep {!/[^A-Za-z0-9+\/=]/} split /\n/, $str;

say decode_base64($sanitized_str);

might be what you want. It produces

This is simple ASCII Base64 for StackOverflow exmaple.

How to use subprocess popen Python

In the recent Python version, subprocess has a big change. It offers a brand-new class Popen to handle os.popen1|2|3|4.

The new subprocess.Popen()

import subprocess
subprocess.Popen('ls -la', shell=True)

Its arguments:

subprocess.Popen(args, 
                bufsize=0, 
                executable=None, 
                stdin=None, stdout=None, stderr=None, 
                preexec_fn=None, close_fds=False, 
                shell=False, 
                cwd=None, env=None, 
                universal_newlines=False, 
                startupinfo=None, 
                creationflags=0)

Simply put, the new Popen includes all the features which were split into 4 separate old popen.

The old popen:

Method  Arguments
popen   stdout
popen2  stdin, stdout
popen3  stdin, stdout, stderr
popen4  stdin, stdout and stderr

You could get more information in Stack Abuse - Robert Robinson. Thank him for his devotion.

Tomcat 7: How to set initial heap size correctly?

Use following command to increase java heap size for tomcat7 (linux distributions) correctly:

echo 'export CATALINA_OPTS="-Xms512M -Xmx1024M"' > /usr/share/tomcat7/bin/setenv.sh

jQuery validate: How to add a rule for regular expression validation?

This worked for me, being one of the validation rules:

    Zip: {
                required: true,
                regex: /^\d{5}(?:[-\s]\d{4})?$/
            }

Hope it helps

Excel function to get first word from sentence in other cell

If you want to cater to 1-word cell, use this... based upon astander's

=IFERROR(LEFT(A1,SEARCH(" ",A1)-1),A1)

Insert 2 million rows into SQL Server quickly

I tried with this method and it significantly reduced my database insert execution time.

List<string> toinsert = new List<string>();
StringBuilder insertCmd = new StringBuilder("INSERT INTO tabblename (col1, col2, col3) VALUES ");

foreach (var row in rows)
{
      // the point here is to keep values quoted and avoid SQL injection
      var first = row.First.Replace("'", "''")
      var second = row.Second.Replace("'", "''")
      var third = row.Third.Replace("'", "''")

      toinsert.Add(string.Format("( '{0}', '{1}', '{2}' )", first, second, third));
}
if (toinsert.Count != 0)
{
      insertCmd.Append(string.Join(",", toinsert));
      insertCmd.Append(";");
}
using (MySqlCommand myCmd = new MySqlCommand(insertCmd.ToString(), SQLconnectionObject))
{
      myCmd.CommandType = CommandType.Text;
      myCmd.ExecuteNonQuery();
}

*Create SQL connection object and replace it where I have written SQLconnectionObject.

HTTPS connections over proxy servers

TLS/SSL (The S in HTTPS) guarantees that there are no eavesdroppers between you and the server you are contacting, i.e. no proxies. Normally, you use CONNECT to open up a TCP connection through the proxy. In this case, the proxy will not be able to cache, read, or modify any requests/responses, and therefore be rather useless.

If you want the proxy to be able to read information, you can take the following approach:

  1. Client starts HTTPS session
  2. Proxy transparently intercepts the connection and returns an ad-hoc generated(possibly weak) certificate Ka, signed by a certificate authority that is unconditionally trusted by the client.
  3. Proxy starts HTTPS session to target
  4. Proxy verifies integrity of SSL certificate; displays error if the cert is not valid.
  5. Proxy streams content, decrypts it and re-encrypts it with Ka
  6. Client displays stuff

An example is Squid's SSL bump. Similarly, burp can be configured to do this. This has also been used in a less-benign context by an Egyptian ISP.

Note that modern websites and browsers can employ HPKP or built-in certificate pins which defeat this approach.

Web API optional parameters

I figured it out. I was using a bad example I found in the past of how to map query string to the method parameters.

In case anyone else needs it, in order to have optional parameters in a query string such as:

  • ~/api/products/filter?apc=AA&xpc=BB
  • ~/api/products/filter?sku=7199123

you would use:

[Route("products/filter/{apc?}/{xpc?}/{sku?}")]
public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

It seems odd to have to define default values for the method parameters when these types already have a default.

Custom CSS Scrollbar for Firefox

I thought I would share my findings in case someone is considering a JQuery plugin to do the job.

I gave JQuery Custom Scrollbar a go. It's pretty fancy and does some smooth scrolling (with scrolling inertia) and has loads of parameters you can tweak, but it ended up being a bit too CPU intensive for me (and it adds a fair amount to the DOM).

Now I'm giving Perfect Scrollbar a go. It's simple and lightweight (6KB) and it's doing a decent job so far. It's not CPU intensive at all (as far as I can tell) and adds very little to your DOM. It's only got a couple of parameters to tweak (wheelSpeed and wheelPropagation), but it's all I need and it handles updates to the scrolling content nicely (such as loading images).

P.S. I did have a quick look at JScrollPane, but @simone is right, it's a bit dated now and a PITA.

Bootstrap how to get text to vertical align in a div container

h2.text-left{
  position:relative;
  top:50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

Explanation:

The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.

Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.

A possible fix for multiple lines would be to use a percentage slightly less than 50%.