Programs & Examples On #Web inspector

Web Inspector is a built-in set of developer tools in WebKit based browsers.

Using Chrome's Element Inspector in Print Preview Mode?

Changed in Chrome 32 35+

(In Chrome 35+ the "Emulation" tab is present by default. Also, the console is available from any primary tab.)

  1. In DevTools, go to settings-> Overrides
  2. enable "Show Emulation view in console drawer"
  3. Close settings, go to 'Elements' tab
  4. Hit Esc to bring up console
  5. Choose tab "Emulation", click "Screen"
  6. Scroll down to "CSS Media", select "print"

This option is not (yet?) available in the console tab.

Enable Overrides

How can I listen for keypress event on the whole page?

Just to add to this in 2019 w Angular 8,

instead of keypress I had to use keydown

@HostListener('document:keypress', ['$event'])

to

@HostListener('document:keydown', ['$event'])

Working Stacklitz

XAMPP on Windows - Apache not starting

I know this is somewhat of an old topic, but in case anyone reads this in the future...

I uninstalled xampp, deleted everything under the c:\xampp folder, then reinstalled xampp as administrator and it worked like a charm.

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):

N[i]/2 will be a float64 but range() expects an integer. Just cast the call to

for j in range(int(N[i]/2)):

C: scanf to array

The %d conversion specifier will only convert one decimal integer. It doesn't know that you're passing an array, it can't modify its behavior based on that. The conversion specifier specifies the conversion.

There is no specifier for arrays, you have to do it explicitly. Here's an example with four conversions:

if(scanf("%d %d %d %d", &array[0], &array[1], &array[2], &array[3]) == 4)
  printf("got four numbers\n");

Note that this requires whitespace between the input numbers.

If the id is a single 11-digit number, it's best to treat as a string:

char id[12];

if(scanf("%11s", id) == 1)
{
  /* inspect the *character* in id[0], compare with '1' or '2' for instance. */
}

How to change a package name in Eclipse?

In pack explorer of eclipse> Single Click on the name of Package> click F2 keyboard key >type new name> click finish.

Eclipse will do the rest of job. It will rename old package name to new in code files also.

How can I do a case insensitive string comparison?

You can (although controverse) extend System.String to provide a case insensitive comparison extension method:

public static bool CIEquals(this String a, String b) {
    return a.Equals(b, StringComparison.CurrentCultureIgnoreCase);
}

and use as such:

x.Username.CIEquals((string)drUser["Username"]);

C# allows you to create extension methods that can serve as syntax suggar in your project, quite useful I'd say.

It's not the answer and I know this question is old and solved, I just wanted to add these bits.

How can I get the number of days between 2 dates in Oracle 11g?

You can try using:

select trunc(sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) as days from dual

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

How can I catch a ctrl-c event?

You have to catch the SIGINT signal (we are talking POSIX right?)

See @Gab Royer´s answer for sigaction.

Example:

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

void my_handler(sig_t s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{
   signal (SIGINT,my_handler);

   while(1);
   return 0;

}

Changing element style attribute dynamically using JavaScript

I resolve similar problem with:

document.getElementById("xyz").style.padding = "10px 0 0 0";

Hope that helps.

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Run XAMPP Control Panel as Administrator if using Windows 7 or more. Windows may block access to ports if not accessed by adminstrator user.

nvm is not compatible with the npm config "prefix" option:

Delete and Reset the prefix

$ npm config delete prefix 
$ npm config set prefix $NVM_DIR/versions/node/v6.11.1

Note: Change the version number with the one indicated in the error message.

nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local" Run "npm config delete prefix" or "nvm use --delete-prefix v6.11.1 --silent" to unset it.


Credits to @gabfiocchi on Github - "You need to overwrite nvm prefix"

VB.NET: Clear DataGridView

Dim DS As New DataSet

DS.Clear() - DATASET clear works better than DataGridView.Rows.Clear() for me :

Public Sub doQuery(sql As String)
   Try
        DS.Clear()  '<-- here
        '   - CONNECT -
        DBCon.Open()
        '   Cmd gets SQL Query
        Cmd = New OleDbCommand(sql, DBCon)
        DA = New OleDbDataAdapter(Cmd)
        DA.Fill(DS)
        '   - DISCONNECT -
        DBCon.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

CSS property to pad text inside of div

Padding is a way to add kind of a margin inside the Div.
Just Use

div { padding-left: 20px; }

And to mantain the size, you would have to -20px from the original width of the Div.

Update Tkinter Label from variable

The window is only displayed once the mainloop is entered. So you won't see any changes you make in your while True block preceding the line root.mainloop().


GUI interfaces work by reacting to events while in the mainloop. Here's an example where the StringVar is also connected to an Entry widget. When you change the text in the Entry widget it automatically changes in the Label.

from tkinter import *

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

t = Entry(root, textvariable = var)
t.pack()

root.mainloop() # the window is now displayed

I like the following reference: tkinter 8.5 reference: a GUI for Python


Here is a working example of what you were trying to do:

from tkinter import *
from time import sleep

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

for i in range(6):
    sleep(1) # Need this to slow the changes down
    var.set('goodbye' if i%2 else 'hello')
    root.update_idletasks()

root.update Enter event loop until all pending events have been processed by Tcl.

Test for array of string type in TypeScript

You cannot test for string[] in the general case but you can test for Array quite easily the same as in JavaScript https://stackoverflow.com/a/767492/390330

If you specifically want for string array you can do something like:

if (Array.isArray(value)) {
   var somethingIsNotString = false;
   value.forEach(function(item){
      if(typeof item !== 'string'){
         somethingIsNotString = true;
      }
   })
   if(!somethingIsNotString && value.length > 0){
      console.log('string[]!');
   }
}

Add a new item to recyclerview programmatically?

if you are adding multiple items to the list use this:

mAdapter.notifyItemRangeInserted(startPosition, itemcount);

This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount

existing item in the dataset still considered up to date.

Build a basic Python iterator

Include the following code in your class code.

 def __iter__(self):
        for x in self.iterable:
            yield x

Make sure that you replace self.iterablewith the iterable which you iterate through.

Here's an example code

class someClass:
    def __init__(self,list):
        self.list = list
    def __iter__(self):
        for x in self.list:
            yield x


var = someClass([1,2,3,4,5])
for num in var: 
    print(num) 

Output

1
2
3
4
5

Note: Since strings are also iterable, they can also be used as an argument for the class

foo = someClass("Python")
for x in foo:
    print(x)

Output

P
y
t
h
o
n

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

Many solutions here did not account for rounding. For example:

Event happened at 3pm two days ago. If you are checking at 2pm, it will show one day ago. If you are checking at 4pm it will show two days ago.

If you are working with unix time, this helps:

// how long since event has passed in seconds
$secs = time() - $time_ago;

// how many seconds in a day
$sec_per_day = 60*60*24;

// days elapsed
$days_elapsed = floor($secs / $sec_per_day);

// how many seconds passed today
$today_seconds = date('G')*3600 + date('i') * 60 + date('s');

// how many seconds passed in the final day calculation
$remain_seconds = $secs % $sec_per_day;

if($today_seconds < $remain_seconds)
{
    $days_elapsed++;
}

echo 'The event was '.$days_ago.' days ago.';

It is not perfect if you are worried about leap seconds and daylight savings time.

List of zeros in python

Here is the xrange way:

list(0 for i in xrange(0,5)) 

Play an audio file using jQuery when a button is clicked

For anyone else following along, I've simply taken Ahmet's answer and updated the original asker's jsfiddle here, substituting:

audio.mp3

for

http://www.uscis.gov/files/nativedocuments/Track%2093.mp3

linking in a freely available mp3 off the web. Thank you for sharing the easy solution!

clear table jquery

The nuclear option:

$("#yourtableid").html("");

Destroys everything inside of #yourtableid. Be careful with your selectors, as it will destroy any html in the selector you pass!

Comparing two joda DateTime instances

DateTime inherits its equals method from AbstractInstant. It is implemented as such

public boolean equals(Object readableInstant) {     // must be to fulfil ReadableInstant contract     if (this == readableInstant) {         return true;     }     if (readableInstant instanceof ReadableInstant == false) {         return false;     }     ReadableInstant otherInstant = (ReadableInstant) readableInstant;     return         getMillis() == otherInstant.getMillis() &&         FieldUtils.equals(getChronology(), otherInstant.getChronology()); } 

Notice the last line comparing chronology. It's possible your instances' chronologies are different.

How to add buttons dynamically to my form?

You aren't creating any buttons, you just have an empty list.

You can forget the list and just create the buttons in the loop.

private void button1_Click(object sender, EventArgs e) 
{     
     int top = 50;
     int left = 100;

     for (int i = 0; i < 10; i++)     
     {         
          Button button = new Button();   
          button.Left = left;
          button.Top = top;
          this.Controls.Add(button);      
          top += button.Height + 2;
     }
} 

What's the difference between using "let" and "var"?

let vs var. It's all about scope.

var variables are global and can be accessed basically everywhere, while let variables are not global and only exist until a closing parenthesis kills them.

See my example below, and note how the lion (let) variable acts differently in the two console.logs; it becomes out of scope in the 2nd console.log.

var cat = "cat";
let dog = "dog";

var animals = () => {
    var giraffe = "giraffe";
    let lion = "lion";

    console.log(cat);  //will print 'cat'.
    console.log(dog);  //will print 'dog', because dog was declared outside this function (like var cat).

    console.log(giraffe); //will print 'giraffe'.
    console.log(lion); //will print 'lion', as lion is within scope.
}

console.log(giraffe); //will print 'giraffe', as giraffe is a global variable (var).
console.log(lion); //will print UNDEFINED, as lion is a 'let' variable and is now out of scope.

Connecting to TCP Socket from browser using javascript

ws2s project is aimed at bring socket to browser-side js. It is a websocket server which transform websocket to socket.

ws2s schematic diagram

enter image description here

code sample:

var socket = new WS2S("wss://ws2s.feling.io/").newSocket()

socket.onReady = () => {
  socket.connect("feling.io", 80)
  socket.send("GET / HTTP/1.1\r\nHost: feling.io\r\nConnection: close\r\n\r\n")
}

socket.onRecv = (data) => {
  console.log('onRecv', data)
}

Python 3 sort a dict by its values

To sort dictionary, we could make use of operator module. Here is the operator module documentation.

import operator                             #Importing operator module
dc =  {"aa": 3, "bb": 4, "cc": 2, "dd": 1}  #Dictionary to be sorted

dc_sort = sorted(dc.items(),key = operator.itemgetter(1),reverse = True)
print dc_sort

Output sequence will be a sorted list :

[('bb', 4), ('aa', 3), ('cc', 2), ('dd', 1)]

If we want to sort with respect to keys, we can make use of

dc_sort = sorted(dc.items(),key = operator.itemgetter(0),reverse = True)

Output sequence will be :

[('dd', 1), ('cc', 2), ('bb', 4), ('aa', 3)]

"use database_name" command in PostgreSQL

In pgAdmin you can also use

SET search_path TO your_db_name;

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

How to find foreign key dependencies in SQL Server?

One that I really like to use is called SQL Dependency Tracker by Red Gate Software. You can put in any database object(s) such as tables, stored procedures, etc. and it will then automatically draw the relationship lines between all the other objects that rely on your selected item(s).

Gives a very good graphical representation of the dependencies in your schema.

List of all special characters that need to be escaped in a regex

You can look at the javadoc of the Pattern class: http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

You need to escape any char listed there if you want the regular char and not the special meaning.

As a maybe simpler solution, you can put the template between \Q and \E - everything between them is considered as escaped.

Xcode is not currently available from the Software Update server

If you are trying this on a latest Mac OS X Mavericks, command line tools come with the Xcode 5.x

So make sure you have installed & updated Xcode to latest

after which make sure Xcode command line tools is pointed correctly using this command

xcode-select -p

Which might show some path like

/Applications/Xcode.app/Contents/Developer

Change the path to correct path using the switch command:

sudo xcode-select --switch /Library/Developer/CommandLineTools/

this should help you set it to correct path, after which you can use the same above command -p to check if it is set correctly

How to test that a registered variable is not empty?

You can check for empty string (when stderr is empty)

- name: Check script
  shell: . {{ venv_name }}/bin/activate && myscritp.py
  args:
    chdir: "{{ home }}"
  sudo_user: "{{ user }}"
  register: test_myscript

- debug: msg='myscritp is Ok'
  when: test_myscript.stderr == ""

If you want to check for fail:

- debug: msg='myscritp has error: {{test_myscript.stderr}}'
  when: test_myscript.stderr != ""

Also look at this stackoverflow question

Arrays.asList() of an array

I think you have found an example where auto-boxing doesn't really work. Because Arrays.asList(T... a) has a varargs parameter the compiler apparently considers the int[] and returns a List<int[]> with a single element in it.

You should change the method into this:

public int getTheNumber(Integer[] factors) {
    ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));  
    Collections.sort(f);
    return f.get(0) * f.get(f.size() - 1);
}

and possibly add this for compatibility

public int getTheNumber(int[] factors) {
    Integer[] factorsInteger = new Integer[factors.length];
    for(int ii=0; ii<factors.length; ++ii) {
        factorsInteger[ii] = factors[ii];
    }

    return getTheNumber(factorsInteger);
}

Vertical align middle with Bootstrap responsive grid

.row {
    letter-spacing: -.31em;
    word-spacing: -.43em;
}
.col-md-4 {
    float: none;
    display: inline-block;
    vertical-align: middle;
}

Note: .col-md-4 could be any grid column, its just an example here.

Sockets - How to find out what port and address I'm assigned

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening:

struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
    perror("getsockname");
else
    printf("port number %d\n", ntohs(sin.sin_port));

As for the IP address, if you use INADDR_ANY then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname() on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.

PivotTable's Report Filter using "greater than"

I can't say how much this might help you, but just found a solution to something similar problem which I faced. In the Pivot-

  1. Right click and choose Pivot table options
  2. Choose the display option
  3. uncheck the first 'Show expand/Collapse buttons'
  4. check the 'Classic PivotTable Layout(enables dragging of fields in the grid)
  5. click ok.

This would refine the data. Then, I had just copy and pasted this data in a new tab wherein I had applied the filters to my Total column with values greater than certain percentage.

This did work in my case and hope it helps you too.

Node.js Port 3000 already in use but it actually isn't?

For windows user, Just simple stop all processes of Node.js in Task Manager

Hope it will help

How to Load Ajax in Wordpress

Personally i prefer to do ajax in wordpress the same way that i would do ajax on any other site. I create a processor php file that handles all my ajax requests and just use that URL. So this is, because of htaccess not exactly possible in wordpress so i do the following.

1.in my htaccess file that lives in my wp-content folder i add this below what's already there

<FilesMatch "forms?\.php$">
Order Allow,Deny
Allow from all
</FilesMatch>

In this case my processor file is called forms.php - you would put this in your wp-content/themes/themeName folder along with all your other files such as header.php footer.php etc... it just lives in your theme root.

2.) In my ajax code i can then use my url like this

$.ajax({
    url:'/wp-content/themes/themeName/forms.php',
    data:({
        someVar: someValue
    }),
    type: 'POST'
});

obviously you can add in any of your before, success or error type things you'd like ...but yea this is (i believe) the easier way to do it because you avoid all the silliness of telling wordpress in 8 different places what's going to happen and this also let's you avoid doing other things you see people doing where they put js code on the page level so they can dip into php where i prefer to keep my js files separate.

Uploading an Excel sheet and importing the data into SQL Server database

You are dealing with a HttpPostedFile; this is the file that is "uploaded" to the web server. You really need to save that file somewhere and then use it, because...

...in your instance, it just so happens to be that you are hosting your website on the same machine the file resides, so the path is accessible. As soon as you deploy your site to a different machine, your code isn't going to work.

Break this down into two steps:

1) Save the file somewhere - it's very common to see this:

string saveFolder = @"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files

string filePath = Path.Combine(saveFolder, FileUpload1.FileName); 

FileUpload1.SaveAs(filePath);

Now you have your file locally and the real work can be done.

2) Get the data from the file. Your code should work as is but you can simply write your connection string this way:

string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath);

You can then think about deleting the file you've just uploaded and imported.

To provide a more concrete example, we can refactor your code into two methods:

    private void SaveFileToDatabase(string filePath)
    {
        String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";

        String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
        //Create Connection to Excel work book 
        using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
        {
            //Create OleDbCommand to fetch data from Excel 
            using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
            {
                excelConnection.Open();
                using (OleDbDataReader dReader = cmd.ExecuteReader())
                {
                    using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
                    {
                        //Give your Destination table name 
                        sqlBulk.DestinationTableName = "Excel_table";
                        sqlBulk.WriteToServer(dReader);
                    }
                }
            }
        } 
    }


    private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
    {


        string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);

        fileUploadControl.SaveAs(filePath);

        return filePath;

    }

You could simply then call SaveFileToDatabase(GetLocalFilePath(@"C:\temp\uploads", FileUpload1));

Consider reviewing the other Extended Properties for your Excel connection string. They come in useful!

Other improvements you might want to make include putting your Sql Database connection string into config, and adding proper exception handling. Please consider this example for demonstration only!

Java JTextField with input hint

Here is a single class copy/paste solution:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.plaf.basic.BasicTextFieldUI;
import javax.swing.text.JTextComponent;


public class HintTextFieldUI extends BasicTextFieldUI implements FocusListener {

    private String hint;
    private boolean hideOnFocus;
    private Color color;

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
        repaint();
    }

    private void repaint() {
        if(getComponent() != null) {
            getComponent().repaint();           
        }
    }

    public boolean isHideOnFocus() {
        return hideOnFocus;
    }

    public void setHideOnFocus(boolean hideOnFocus) {
        this.hideOnFocus = hideOnFocus;
        repaint();
    }

    public String getHint() {
        return hint;
    }

    public void setHint(String hint) {
        this.hint = hint;
        repaint();
    }
    public HintTextFieldUI(String hint) {
        this(hint,false);
    }

    public HintTextFieldUI(String hint, boolean hideOnFocus) {
        this(hint,hideOnFocus, null);
    }

    public HintTextFieldUI(String hint, boolean hideOnFocus, Color color) {
        this.hint = hint;
        this.hideOnFocus = hideOnFocus;
        this.color = color;
    }

    @Override
    protected void paintSafely(Graphics g) {
        super.paintSafely(g);
        JTextComponent comp = getComponent();
        if(hint!=null && comp.getText().length() == 0 && (!(hideOnFocus && comp.hasFocus()))){
            if(color != null) {
                g.setColor(color);
            } else {
                g.setColor(comp.getForeground().brighter().brighter().brighter());              
            }
            int padding = (comp.getHeight() - comp.getFont().getSize())/2;
            g.drawString(hint, 2, comp.getHeight()-padding-1);          
        }
    }

    @Override
    public void focusGained(FocusEvent e) {
        if(hideOnFocus) repaint();

    }

    @Override
    public void focusLost(FocusEvent e) {
        if(hideOnFocus) repaint();
    }
    @Override
    protected void installListeners() {
        super.installListeners();
        getComponent().addFocusListener(this);
    }
    @Override
    protected void uninstallListeners() {
        super.uninstallListeners();
        getComponent().removeFocusListener(this);
    }
}

Use it like this:

TextField field = new JTextField();
field.setUI(new HintTextFieldUI("Search", true));

Note that it is happening in protected void paintSafely(Graphics g).

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

I have fixed it with removing below code from

C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf file

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/Apache24/docs/dummy-host.example.com"
    ServerName dummy-host.example.com
    ServerAlias www.dummy-host.example.com
    ErrorLog "logs/dummy-host.example.com-error.log"
    CustomLog "logs/dummy-host.example.com-access.log" common
 </VirtualHost>

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/Apache24/docs/dummy-host2.example.com"
    ServerName dummy-host2.example.com
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

And added

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot "c:/wamp/www"
    ServerName localhost
    ErrorLog "logs/localhost-error.log"
    CustomLog "logs/localhost-access.log" common
</VirtualHost>

And it has worked like charm

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

Align contents inside a div

Honestly, I hate all the solutions I've seen so far, and I'll tell you why: They just don't seem to ever align it right...so here's what I usually do:

I know what pixel values each div and their respective margins hold...so I do the following.

I'll create a wrapper div that has an absolute position and a left value of 50%...so this div now starts in the middle of the screen, and then I subtract half of all the content of the div's width...and I get BEAUTIFULLY scaling content...and I think this works across all browsers, too. Try it for yourself (this example assumes all content on your site is wrapped in a div tag that uses this wrapper class and all content in it is 200px in width):

.wrapper {
    position: absolute;
    left: 50%;
    margin-left: -100px;
}

EDIT: I forgot to add...you may also want to set width: 0px; on this wrapper div for some browsers to not show the scrollbars, and then you may use absolute positioning for all inner divs.

This also works AMAZING for vertically aligning your content as well using top: 50% and margin-top. Cheers!

Show div #id on click with jQuery

You can use jQuery toggle to show and hide the div. The script will be like this

  <script type="text/javascript">
    jQuery(function(){
      jQuery("#music").click(function () {
        jQuery("#musicinfo").toggle("slow");
      });
    });
</script>

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

Unzip All Files In A Directory

for i in `ls *.zip`; do unzip $i; done

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

This is reviving an old question, but in Python 3, you can just use bytes directly:

>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'

MVC Razor Hidden input and passing values

First of all ASP.NET MVC does not work the same way WebForms does. You don't have the whole runat="server" thing. MVC does not offer the abstraction layer that WebForms offered. Probabaly you should try to understand what controllers and actions are and then you should look at model binding. Any beginner level tutorial about MVC shows how you can pass data between the client and the server.

bash script use cut command at variable and store result at another variable

You can avoid the loop and cut etc by using:

awk -F ':' '{system("ping " $1);}' config.txt

However it would be better if you post a snippet of your config.txt

Activating Anaconda Environment in VsCode

Setting python.pythonPath in VSCode's settings.json file doesn't work for me, but another method does. According to the Anaconda documentation at Microsoft Visual Studio Code (VS Code):

When you launch VS Code from Navigator, VS Code is configured to use the Python interpreter in the currently selected environment.

Anaconda Navigator

How to pass arguments to entrypoint in docker-compose.yml

Whatever is specified in the command in docker-compose.yml should get appended to the entrypoint defined in the Dockerfile, provided entrypoint is defined in exec form in the Dockerfile.

If the EntryPoint is defined in shell form, then any CMD arguments will be ignored.

react-native :app:installDebug FAILED

I couldn't get it to work with a hardware device. I kept getting the same error, but...

For your emulator you have to choose the IntelX86 Atom System image. Then ADB will connect to your emulator and it will properly install the installDebug.apk.

This is what I had to do.

Also look at this tutorial. It helped me immensely.

https://www.youtube.com/watch?v=cnqyUnASuk8

What is the difference between an interface and abstract class?

The topic of abstract classes vs interfaces is mostly about semantics.

Abstract classes act in different programming languages often as a superset of interfaces, except one thing and that is, that you can implement multiple interfaces, but inherit only one class.

An interface defines what something must be able to do; like a contract, but does not provide an implementation of it.

An abstract class defines what something is and it commonly hosts shared code between the subclasses.

For example a Formatter should be able to format() something. The common semantics to describe something like that would be to create an interface IFormatter with a declaration of format() that acts like a contract. But IFormatter does not describe what something is, but just what it should be able to to. The common semantics to describe what something actually is, is to create a class. In this case we create an abstract class... So we create an abstract class Formatter which implements the interface. That is a very descriptive code, because we now know we have a Formatter and we now know what every Formatter must be able to do.

Also one very important topic is documentation (at least for some people...). In your documentation you probably want to explain within your subclasses what a Formatter actually is. It is very convenient to have an abstract class Formatter to which documentation you can link to within your subclasses. That is very convenient and generic. On the other hand if you do not have an abstract class Formatter and only an interface IFormatter you would have to explain in each of your subclasses what a Formatter actucally is, because an interface is a contract and you would not describe what a Formatter actually is within the documentation of an interface — at least it would be not something common to do and you would break the semantics that most developers consider to be correct.

Note: It is a very common pattern to make an abstract class implement an interface.

Changing an AIX password via script?

If you can use ansible, and set the sudo rights in it, then you can easily use this script. If you're wanting to script something like this, it means you need to do it on more than one system. Therefore, you should try to automate that as well.

How to run code after some delay in Flutter?

Just leaving here the snippet everyone is looking for:

Future.delayed(Duration(milliseconds: 100), () {
  // Do something
});

React.js: Wrapping one component into another

In addition to Sophie's answer, I also have found a use in sending in child component types, doing something like this:

var ListView = React.createClass({
    render: function() {
        var items = this.props.data.map(function(item) {
            return this.props.delegate({data:item});
        }.bind(this));
        return <ul>{items}</ul>;
    }
});

var ItemDelegate = React.createClass({
    render: function() {
        return <li>{this.props.data}</li>
    }
});

var Wrapper = React.createClass({    
    render: function() {
        return <ListView delegate={ItemDelegate} data={someListOfData} />
    }
});

Set Jackson Timezone for Date deserialization

Have you tried this in your application.properties?

spring.jackson.time-zone= # Time zone used when formatting dates. For instance `America/Los_Angeles`

How to toggle a boolean?

bool = bool != true;

One of the cases.

How to subtract 2 hours from user's local time?

According to Javascript Date Documentation, you can easily do this way:

var twoHoursBefore = new Date();
twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);

And don't worry about if hours you set will be out of 0..23 range. Date() object will update the date accordingly.

Visual Studio debugging/loading very slow

In my case the problem was an external running exe file - namely:

WUDFCompanionHost.exe

under the name of

"Windows Driver Foundation - User-mode Driver Companion Framework Host Process".

Process, which has taken a steady 10% of the CPU. Killing it helped directly and withing a second the page has loaded.

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

I discovered this error on a recent application project. I was writing to run from the command line or the browser window, so I was using server detection to get the relative URL of the document I was asking for. The trouble was, the site is https, and each time I attempted to access http://(same server), cURL helpfully changed it to https.

This works fine from the browser, but from the command-line, I'd then get an SSL error even with both verify's set to false. What I had to do was,

1) Check $_SERVER['HTTP_HOST']. If present, use ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST']

2) Check $_SERVER['COMPUTERNAME'], and if it matched the production server, provide the https URL. ("https://(servername)")

3) If neither condition passed, it means I'm running command-line on a different server, and use "http://localhost".

Now, this worked, but it's a hack. Also, I never did figure out why on one server (https) cURL changed my URL, while on the other (also https) it left my URL alone.

Weird.

ISO time (ISO 8601) in Python

The ISO 8601 time format does not store a time zone name, only the corresponding UTC offset is preserved.

To convert a file ctime to an ISO 8601 time string while preserving the UTC offset in Python 3:

>>> import os
>>> from datetime import datetime, timezone
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, timezone.utc)
>>> dt.astimezone().isoformat()
'2015-11-27T00:29:06.839600-05:00'

The code assumes that your local timezone is Eastern Time Zone (ET) and that your system provides a correct UTC offset for the given POSIX timestamp (ts), i.e., Python has access to a historical timezone database on your system or the time zone had the same rules at a given date.

If you need a portable solution; use the pytz module that provides access to the tz database:

>>> import os
>>> from datetime import datetime
>>> import pytz  # pip install pytz
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, pytz.timezone('America/New_York'))
>>> dt.isoformat()
'2015-11-27T00:29:06.839600-05:00'

The result is the same in this case.

If you need the time zone name/abbreviation/zone id, store it separately.

>>> dt.astimezone().strftime('%Y-%m-%d %H:%M:%S%z (%Z)')
'2015-11-27 00:29:06-0500 (EST)'

Note: no, : in the UTC offset and EST timezone abbreviation is not part of the ISO 8601 time format. It is not unique.

Different libraries/different versions of the same library may use different time zone rules for the same date/timezone. If it is a future date then the rules might be unknown yet. In other words, the same UTC time may correspond to a different local time depending on what rules you use -- saving a time in ISO 8601 format preserves UTC time and the local time that corresponds to the current time zone rules in use on your platform. You might need to recalculate the local time on a different platform if it has different rules.

When is JavaScript synchronous?

To someone who really understands how JS works this question might seem off, however most people who use JS do not have such a deep level of insight (and don't necessarily need it) and to them this is a fairly confusing point, I will try to answer from that perspective.

JS is synchronous in the way its code is executed. each line only runs after the line before it has completed and if that line calls a function after that is complete etc...

The main point of confusion arises from the fact that your browser is able to tell JS to execute more code at anytime (similar to how you can execute more JS code on a page from the console). As an example JS has Callback functions who's purpose is to allow JS to BEHAVE asynchronously so further parts of JS can run while waiting for a JS function that has been executed (I.E. a GET call) to return back an answer, JS will continue to run until the browser has an answer at that point the event loop (browser) will execute the JS code that calls the callback function.

Since the event loop (browser) can input more JS to be executed at any point in that sense JS is asynchronous (the primary things that will cause a browser to input JS code are timeouts, callbacks and events)

I hope this is clear enough to be helpful to somebody.

How to check if an appSettings key exists?

Safely returned default value via generics and LINQ.

public T ReadAppSetting<T>(string searchKey, T defaultValue, StringComparison compare = StringComparison.Ordinal)
{
    if (ConfigurationManager.AppSettings.AllKeys.Any(key => string.Compare(key, searchKey, compare) == 0)) {
        try
        { // see if it can be converted.
            var converter = TypeDescriptor.GetConverter(typeof(T));
            if (converter != null) defaultValue = (T)converter.ConvertFromString(ConfigurationManager.AppSettings.GetValues(searchKey).First());
        }
        catch { } // nothing to do just return the defaultValue
    }
    return defaultValue;
}

Used as follows:

string LogFileName = ReadAppSetting("LogFile","LogFile");
double DefaultWidth = ReadAppSetting("Width",1280.0);
double DefaultHeight = ReadAppSetting("Height",1024.0);
Color DefaultColor = ReadAppSetting("Color",Colors.Black);

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

Split and join C# string

You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.

string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');

if (lnSpace > -1)
{
    string lcFirst = lcStart.Substring(0, lnSpace);
    string lcRest = lcStart.Substring(lnSpace + 1);
}

Android Studio Gradle Already disposed Module

For an alternative solution, check if you added your app to settings.gradle successfully

include ':app' 

MongoDB running but can't connect using shell

Not so much an answer but more of an FYI:I've just hit this and found this question as a result of searching. Here is the details of my experience:

Shell error

markdsievers@ip-xx-xx-xx-xx:~$ mongo
MongoDB shell version: 2.0.1
connecting to: test
Wed Dec 21 03:36:13 Socket recv() errno:104 Connection reset by peer 127.0.0.1:27017
Wed Dec 21 03:36:13 SocketException: remote: 127.0.0.1:27017 error: 9001 socket exception [1] server [127.0.0.1:27017] 
Wed Dec 21 03:36:13 DBClientCursor::init call() failed
Wed Dec 21 03:36:13 Error: Error during mongo startup. :: caused by :: DBClientBase::findN: transport error: 127.0.0.1 query: { whatsmyuri: 1 } shell/mongo.js:84
exception: connect failed

Mongo logs reveal

Wed Dec 21 03:35:04 [initandlisten] connection accepted from 127.0.0.1:50273 #6612
Wed Dec 21 03:35:04 [initandlisten] connection refused because too many open connections: 819

This perhaps indicates the other answer (JaKi) was experiencing the same thing, where some connections were purged and access made possible again for the shell (other clients)

How to wrap text using CSS?

With text-wrap, browser support is relatively weak (as you might expect from from a draft spec).

You are better off taking steps to ensure the data doesn't have long strings of non-white-space.

Bootstrap 4 - Inline List?

Bootstrap4

Remove a list’s bullets and apply some light margin with a combination of two classes, .list-inline and .list-inline-item.

<ul class="list-inline">
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>

Trying to include a library, but keep getting 'undefined reference to' messages

If the .c source files are converted .cpp (like as in parsec), then the extern needs to be followed by "C" as in

extern "C" void foo();

How do I add a auto_increment primary key in SQL Server database?

It can be done in a single command. You need to set the IDENTITY property for "auto number":

ALTER TABLE MyTable ADD mytableID int NOT NULL IDENTITY (1,1) PRIMARY KEY

More precisely, to set a named table level constraint:

ALTER TABLE MyTable
   ADD MytableID int NOT NULL IDENTITY (1,1),
   CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED (MyTableID)

See ALTER TABLE and IDENTITY on MSDN

convert big endian to little endian in C [without using provided func]

Assuming what you need is a simple byte swap, try something like

Unsigned 16 bit conversion:

swapped = (num>>8) | (num<<8);

Unsigned 32-bit conversion:

swapped = ((num>>24)&0xff) | // move byte 3 to byte 0
                    ((num<<8)&0xff0000) | // move byte 1 to byte 2
                    ((num>>8)&0xff00) | // move byte 2 to byte 1
                    ((num<<24)&0xff000000); // byte 0 to byte 3

This swaps the byte orders from positions 1234 to 4321. If your input was 0xdeadbeef, a 32-bit endian swap might have output of 0xefbeadde.

The code above should be cleaned up with macros or at least constants instead of magic numbers, but hopefully it helps as is

EDIT: as another answer pointed out, there are platform, OS, and instruction set specific alternatives which can be MUCH faster than the above. In the Linux kernel there are macros (cpu_to_be32 for example) which handle endianness pretty nicely. But these alternatives are specific to their environments. In practice endianness is best dealt with using a blend of available approaches

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

For the record only, to add to Spudley's answer, there is also the possibility to use position: absolute and margins if you know the column widths.

For me, the main issue when chossing a method is whether you need the columns to fill the whole height (equal heights), where table-cell is the easiest method (if you don't care much for older browsers).

How to form a correct MySQL connection string?

Here is an example:

MySqlConnection con = new MySqlConnection(
    "Server=ServerName;Database=DataBaseName;UID=username;Password=password");

MySqlCommand cmd = new MySqlCommand(
    " INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
    OSGconv.deciLon+"')", con);

con.Open();
cmd.ExecuteNonQuery();
con.Close();

How to reset sequence in postgres and fill id column with new data?

In my case, I achieved this with:

ALTER SEQUENCE table_tabl_id_seq RESTART WITH 6;

Where my table is named table

Validate IPv4 address in Java

If you don care about the range, the following expression will be useful to validate from 1.1.1.1 to 999.999.999.999

"[1-9]{1,3}\\.[1-9]{1,3}\\.[1-9]{1,3}\\.[1-9]{1,3}"

if (boolean == false) vs. if (!boolean)

This is a style choice. It does not impact the performance of the code in the least, it just makes it more verbose for the reader.

Refreshing Web Page By WebDriver When Waiting For Specific Condition

In Python there is a method for doing this: driver.refresh(). It may not be the same in Java.

Alternatively, you could driver.get("http://foo.bar");, although I think the refresh method should work just fine.

Angular 2 filter/search list

Pipes in Angular 2+ are a great way to transform and format data right from your templates.

Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.

List of Built-in Pipes from API List Examples

{{ user.name | uppercase }}

Example of Angular version 4.4.7. ng version


Custom Pipes which accepts multiple arguments.

HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS   « transform(json: any[], args: any[]) : any[] { ... }

Filtering the content using a Pipe « json-filter-by.pipe.ts

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]) : any[] {
    var searchText = args[0];
    var jsonKey = args[1];

    // json = undefined, args = (2) [undefined, "name"]
    if(searchText == null || searchText == 'undefined') return json;
    if(jsonKey    == null || jsonKey    == 'undefined') return json;

    // Copy all objects of original array into new Array.
    var returnObjects = json;
    json.forEach( function ( filterObjectEntery ) {

      if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
        console.log('Search key is available in JSON object.');

        if ( typeof filterObjectEntery[jsonKey] != "undefined" && 
        filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
            // object value contains the user provided text.
        } else {
            // object didn't match a filter value so remove it from array via filter
            returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
        }
      } else {
        console.log('Search key is not available in JSON object.');
      }

    })
    return returnObjects;
  }
}

Add to @NgModule « Add JsonFilterByPipe to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy. If you add to module then it is available to all the component's of that module.

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule, ReactiveFormsModule,
  ],
  providers: [ StudentDetailsService ],
  declarations: [
    UsersComponent, UserComponent,

    JsonFilterByPipe,
  ],
  exports : [UsersComponent, UserComponent]
})
export class UsersModule {
    // ...
}

File Name: users.component.ts and StudentDetailsService is created from this link.

import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: [ './users.component.css' ],

  providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy  {

  students: MyStudents[];
  selectedStudent: MyStudents;

  constructor(private studentService: StudentDetailsService) { }

  ngOnInit(): void {
    this.loadAllUsers();
  }
  ngOnDestroy(): void {
    // ONDestroy to prevent memory leaks
  }

  loadAllUsers(): void {
    this.studentService.getStudentsList().then(students => this.students = students);
  }

  onSelect(student: MyStudents): void {
    this.selectedStudent = student;
  }

}

File Name: users.component.html

<div>
    <br />
    <div class="form-group">
        <div class="col-md-6" >
            Filter by Name: 
            <input type="text" [(ngModel)]="searchText" 
                   class="form-control" placeholder="Search By Category" />
        </div>
    </div>

    <h2>Present are Students</h2>
    <ul class="students">
    <li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
        <a *ngIf="student" routerLink="/users/update/{{student.id}}">
            <span class="badge">{{student.id}}</span> {{student.name | uppercase}}
        </a>
    </li>
    </ul>
</div>

Java: Integer equals vs. ==

As well for correctness of using == you can just unbox one of compared Integer values before doing == comparison, like:

if ( firstInteger.intValue() == secondInteger ) {..

The second will be auto unboxed (of course you have to check for nulls first).

How to code a very simple login system with java

import java.<span class="q39pbqr9" id="q39pbqr9_9">net</span>.*;
import java.io.*;

<span class="q39pbqr9" id="q39pbqr9_1">public class</span> A
{
    static String user = "user";
    static String pass = "pass";
    static String param_user = "username";
    static String param_pass = "password";
    static String content = "";
    static String action = "action_url";
    static String urlName = "url_name";
    public static void main(String[] args)
    {
        try
        {
            user = URLEncoder.encode(user, "UTF-8");
            pass = URLEncoder.encode(pass, "UTF-8");
            content = "action=" + action +"&amp;" + param_user +"=" + user + "&amp;" + param_pass + "=" + pass;
            URL url = new URL(urlName);
            HttpURLConnection urlConnection = (HttpURLConnection)(url.openConnection());
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setRequestMethod("POST");
            DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
            dataOutputStream.writeBytes(content);
            dataOutputStream.flush();
            dataOutputStream.close();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String responeLine;
            StringBuilder response = new StringBuilder();
            while ((responeLine = bufferedReader.readLine()) != null)
            {
                response.append(responeLine);
            }
            System.out.println(response);
        }catch(Exception ex){ex.printStackTrace();}
    }

Rank function in MySQL

Combination of Daniel's and Salman's answer. However the rank will not give as continues sequence with ties exists . Instead it skips the rank to next. So maximum always reach row count.

    SELECT    first_name,
              age,
              gender,
              IF(age=@_last_age,@curRank:=@curRank,@curRank:=@_sequence) AS rank,
              @_sequence:=@_sequence+1,@_last_age:=age
    FROM      person p, (SELECT @curRank := 1, @_sequence:=1, @_last_age:=0) r
    ORDER BY  age;

Schema and Test Case:

CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1));

INSERT INTO person VALUES (1, 'Bob', 25, 'M');
INSERT INTO person VALUES (2, 'Jane', 20, 'F');
INSERT INTO person VALUES (3, 'Jack', 30, 'M');
INSERT INTO person VALUES (4, 'Bill', 32, 'M');
INSERT INTO person VALUES (5, 'Nick', 22, 'M');
INSERT INTO person VALUES (6, 'Kathy', 18, 'F');
INSERT INTO person VALUES (7, 'Steve', 36, 'M');
INSERT INTO person VALUES (8, 'Anne', 25, 'F');
INSERT INTO person VALUES (9, 'Kamal', 25, 'M');
INSERT INTO person VALUES (10, 'Saman', 32, 'M');

Output:

+------------+------+--------+------+--------------------------+-----------------+
| first_name | age  | gender | rank | @_sequence:=@_sequence+1 | @_last_age:=age |
+------------+------+--------+------+--------------------------+-----------------+
| Kathy      |   18 | F      |    1 |                        2 |              18 |
| Jane       |   20 | F      |    2 |                        3 |              20 |
| Nick       |   22 | M      |    3 |                        4 |              22 |
| Kamal      |   25 | M      |    4 |                        5 |              25 |
| Anne       |   25 | F      |    4 |                        6 |              25 |
| Bob        |   25 | M      |    4 |                        7 |              25 |
| Jack       |   30 | M      |    7 |                        8 |              30 |
| Bill       |   32 | M      |    8 |                        9 |              32 |
| Saman      |   32 | M      |    8 |                       10 |              32 |
| Steve      |   36 | M      |   10 |                       11 |              36 |
+------------+------+--------+------+--------------------------+-----------------+

Decimal to Hexadecimal Converter in Java

Check out the code below for decimal to hexadecimal conversion,

import java.util.Scanner;

public class DecimalToHexadecimal
{
   public static void main(String[] args)
   {
      int temp, decimalNumber;
      String hexaDecimal = "";
      char hexa[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter decimal number : ");
      decimalNumber = sc.nextInt();

      while(decimalNumber > 0)
      {
         temp = decimalNumber % 16;
         hexaDecimal = hexa[temp] + hexaDecimal;
         decimalNumber = decimalNumber / 16;
      }

      System.out.print("The hexadecimal value of " + decimalNumber + " is : " + hexaDecimal);      
      sc.close();
   }
}

You can learn more on different ways to convert decimal to hexadecimal in the following link >> java convert decimal to hexadecimal.

MVC Return Partial View as JSON

Url.Action("Evil", model)

will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

For those like me who are brand new to this, here is code with const and an actual way to compare the byte[]'s. I got all of this code from stackoverflow but defined consts so values could be changed and also

// 24 = 192 bits
    private const int SaltByteSize = 24;
    private const int HashByteSize = 24;
    private const int HasingIterationsCount = 10101;


    public static string HashPassword(string password)
    {
        // http://stackoverflow.com/questions/19957176/asp-net-identity-password-hashing

        byte[] salt;
        byte[] buffer2;
        if (password == null)
        {
            throw new ArgumentNullException("password");
        }
        using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, SaltByteSize, HasingIterationsCount))
        {
            salt = bytes.Salt;
            buffer2 = bytes.GetBytes(HashByteSize);
        }
        byte[] dst = new byte[(SaltByteSize + HashByteSize) + 1];
        Buffer.BlockCopy(salt, 0, dst, 1, SaltByteSize);
        Buffer.BlockCopy(buffer2, 0, dst, SaltByteSize + 1, HashByteSize);
        return Convert.ToBase64String(dst);
    }

    public static bool VerifyHashedPassword(string hashedPassword, string password)
    {
        byte[] _passwordHashBytes;

        int _arrayLen = (SaltByteSize + HashByteSize) + 1;

        if (hashedPassword == null)
        {
            return false;
        }

        if (password == null)
        {
            throw new ArgumentNullException("password");
        }

        byte[] src = Convert.FromBase64String(hashedPassword);

        if ((src.Length != _arrayLen) || (src[0] != 0))
        {
            return false;
        }

        byte[] _currentSaltBytes = new byte[SaltByteSize];
        Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);

        byte[] _currentHashBytes = new byte[HashByteSize];
        Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);

        using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
        {
            _passwordHashBytes = bytes.GetBytes(SaltByteSize);
        }

        return AreHashesEqual(_currentHashBytes, _passwordHashBytes);

    }

    private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
    {
        int _minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
        var xor = firstHash.Length ^ secondHash.Length;
        for (int i = 0; i < _minHashLength; i++)
            xor |= firstHash[i] ^ secondHash[i];
        return 0 == xor;
    }

In in your custom ApplicationUserManager, you set the PasswordHasher property the name of the class which contains the above code.

Ajax LARAVEL 419 POST error

Had the same problem, regenerating application key helped - php artisan key:generate

Basic calculator in Java

import java.util.Scanner;
public class AdditionGame {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    int num1;
    int num2;
    String operation;

    Scanner input = new Scanner(System.in);

    System.out.println("Please Enter The First Number");
    num1 = input.nextInt();

    System.out.println("Please Enter The Second Number");
    num2 = input.nextInt();

    Scanner op = new Scanner (System.in);

    System.out.println("Please Enter The Operation");
    operation = op.next();

    if (operation.equals("+"))
    {
        System.out.println("Your Answer is "+(num1 + num2));
    }
    else if (operation.equals("-"))
    {
        System.out.println("Your Answer is "+(num1 - num2));
    }       
    else if (operation.equals("*"))
    {
        System.out.println("Your Answer is "+(num1 * num2));
    }   
    else if (operation.equals("/"))
    {
        System.out.println("Your Answer is "+(num1 / num2));
    }
}

}

HTML image bottom alignment inside DIV container

This is your code: http://jsfiddle.net/WSFnX/

Using display: table-cell is fine, provided that you're aware that it won't work in IE6/7. Other than that, it's safe: Is there a disadvantage of using `display:table-cell`on divs?

To fix the space at the bottom, add vertical-align: bottom to the actual imgs:

http://jsfiddle.net/WSFnX/1/

Removing the space between the images boils down to this: bikeshedding CSS3 property alternative?

So, here's a demo with the whitespace removed in your HTML: http://jsfiddle.net/WSFnX/4/

Maximum number of records in a MySQL database table

According to Scalability and Limits section in http://dev.mysql.com/doc/refman/5.6/en/features.html, MySQL support for large databases. They use MySQL Server with databases that contain 50 million records. Some users use MySQL Server with 200,000 tables and about 5,000,000,000 rows.

What is the correct way to start a mongod service on linux / OS X?

Homebrew's services tap integrates formulas with the launchctl manager. Adding it is easy:

brew tap homebrew/services

You can then launch MongoDB with this command (this will also start mongodb on boot):

brew services start mongodb

You can also use stop or restart:

brew services stop mongodb
brew services restart mongodb

Passing an array by reference

It's a syntax for array references - you need to use (&array) to clarify to the compiler that you want a reference to an array, rather than the (invalid) array of references int & array[100];.

EDIT: Some clarification.

void foo(int * x);
void foo(int x[100]);
void foo(int x[]);

These three are different ways of declaring the same function. They're all treated as taking an int * parameter, you can pass any size array to them.

void foo(int (&x)[100]);

This only accepts arrays of 100 integers. You can safely use sizeof on x

void foo(int & x[100]); // error

This is parsed as an "array of references" - which isn't legal.

What's the difference between 'git merge' and 'git rebase'?

Git rebase is closer to a merge. The difference in rebase is:

  • the local commits are removed temporally from the branch.
  • run the git pull
  • insert again all your local commits.

So that means that all your local commits are moved to the end, after all the remote commits. If you have a merge conflict, you have to solve it too.

How to utilize date add function in Google spreadsheet?

As with @kidbrax's answer, you can use the + to add days. To get this to work I had to explicitly declare my cell data as being a date:

A1: =DATE(2014, 03, 28)

A2: =A1+1

Value of A2 is now 29th March 2014

Why use deflate instead of gzip for text files served by Apache?

if I remember correctly

  • gzip will compress a little more than deflate
  • deflate is more efficient

How to loop an object in React?

The problem is the way you're using forEach(), as it will always return undefined. You're probably looking for the map() method, which returns a new array:

var tifOptions = Object.keys(tifs).map(function(key) {
    return <option value={key}>{tifs[key]}</option>
});

If you still want to use forEach(), you'd have to do something like this:

var tifOptions = [];

Object.keys(tifs).forEach(function(key) {
    tifOptions.push(<option value={key}>{tifs[key]}</option>);
});

Update:

If you're writing ES6, you can accomplish the same thing a bit neater using an arrow function:

const tifOptions = Object.keys(tifs).map(key => 
    <option value={key}>{tifs[key]}</option>
)

Here's a fiddle showing all options mentioned above: https://jsfiddle.net/fs7sagep/

Which versions of SSL/TLS does System.Net.WebRequest support?

When using System.Net.WebRequest your application will negotiate with the server to determine the highest TLS version that both your application and the server support, and use this. You can see more details on how this works here:

http://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake

If the server doesn't support TLS it will fallback to SSL, therefore it could potentially fallback to SSL3. You can see all of the versions that .NET 4.5 supports here:

http://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.110).aspx

In order to prevent your application being vulnerable to POODLE, you can disable SSL3 on the machine that your application is running on by following this explanation:

https://serverfault.com/questions/637207/on-iis-how-do-i-patch-the-ssl-3-0-poodle-vulnerability-cve-2014-3566

How to make full screen background in a web page

its very simple use this css (replace image.jpg with your background image)

body{height:100%;
   width:100%;
   background-image:url(image.jpg);/*your background image*/  
   background-repeat:no-repeat;/*we want to have one single image not a repeated one*/  
   background-size:cover;/*this sets the image to fullscreen covering the whole screen*/  
   /*css hack for ie*/     
   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.image.jpg',sizingMethod='scale');
   -ms-filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='image.jpg',sizingMethod='scale')";
}

How to make a rest post call from ReactJS code?

Here is an example: https://jsfiddle.net/69z2wepo/9888/

$.ajax({
    type: 'POST',
    url: '/some/url',
    data: data
  })
  .done(function(result) {
    this.clearForm();
    this.setState({result:result});   
  }.bind(this)
  .fail(function(jqXhr) {
    console.log('failed to register');
  });

It used jquery.ajax method but you can easily replace it with AJAX based libs like axios, superagent or fetch.

Install a module using pip for specific python version

You can use this syntax

python_version -m pip install your_package

For example. If you're running python3.5, you named it as "python3", and want to install numpy package

python3 -m pip install numpy

Why do we need to use flatMap?

With flatMap

var requestStream = Rx.Observable.just('https://api.github.com/users');

var responseMetastream = requestStream
  .flatMap(function(requestUrl) {
    return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
  });

responseMetastream.subscribe(json => {console.log(json)})

Without flatMap

var requestStream = Rx.Observable.just('https://api.github.com/users');

var responseMetastream = requestStream
  .map(function(requestUrl) {
    return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
  });

responseMetastream.subscribe(jsonStream => {
  jsonStream.subscribe(json => {console.log(json)})
})

How do you Encrypt and Decrypt a PHP String?

These are compact methods to encrypt / decrypt strings with PHP using AES256 CBC:

function encryptString($plaintext, $password, $encoding = null) {
    $iv = openssl_random_pseudo_bytes(16);
    $ciphertext = openssl_encrypt($plaintext, "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, $iv);
    $hmac = hash_hmac('sha256', $ciphertext.$iv, hash('sha256', $password, true), true);
    return $encoding == "hex" ? bin2hex($iv.$hmac.$ciphertext) : ($encoding == "base64" ? base64_encode($iv.$hmac.$ciphertext) : $iv.$hmac.$ciphertext);
}

function decryptString($ciphertext, $password, $encoding = null) {
    $ciphertext = $encoding == "hex" ? hex2bin($ciphertext) : ($encoding == "base64" ? base64_decode($ciphertext) : $ciphertext);
    if (!hash_equals(hash_hmac('sha256', substr($ciphertext, 48).substr($ciphertext, 0, 16), hash('sha256', $password, true), true), substr($ciphertext, 16, 32))) return null;
    return openssl_decrypt(substr($ciphertext, 48), "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, substr($ciphertext, 0, 16));
}

Usage:

$enc = encryptString("mysecretText", "myPassword");
$dec = decryptString($enc, "myPassword");

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

On Solaris the limit has been about 3.5 GB since Solaris 2.5. (about 10 years ago)

How to query SOLR for empty fields?

Try this:

?q=-id:["" TO *]

Recommendation for compressing JPG files with ImageMagick

I use always:

  • quality in 85
  • progressive (comprobed compression)
  • a very tiny gausssian blur to optimize the size (0.05 or 0.5 of radius) depends on the quality and size of the picture, this notably optimizes the size of the jpeg.
  • Strip any comment or EXIF metadata

in imagemagick should be

convert -strip -interlace Plane -gaussian-blur 0.05 -quality 85% source.jpg result.jpg

or in the newer version:

magick source.jpg -strip -interlace Plane -gaussian-blur 0.05 -quality 85% result.jpg

Source.

From @Fordi in the comments (Don't forget to upvote him if you like this): If you dislike blurring, use -sampling-factor 4:2:0 instead. What this does is reduce the chroma channel's resolution to half, without messing with the luminance resolution that your eyes latch onto. If you want better fidelity in the conversion, you can get a slight improvement without an increase in filesize by specifying -define jpeg:dct-method=float - that is, use the more accurate floating point discrete cosine transform, rather than the default fast integer version.

Set the table column width constant regardless of the amount of text in its cells?

If you need one ore more fixed-width columns while other columns should resize, try setting both min-width and max-width to the same value.

How to configure welcome file list in web.xml

You need to put the JSP file in /index.jsp instead of in /WEB-INF/jsp/index.jsp. This way the whole servlet is superflous by the way.

WebContent
 |-- META-INF
 |-- WEB-INF
 |    `-- web.xml
 `-- index.jsp

If you're absolutely positive that you need to invoke a servlet this strange way, then you should map it on an URL pattern of /index.jsp instead of /index. You only need to change it to get the request dispatcher from request instead of from config and get rid of the whole init() method.

In case you actually intend to have a "home page servlet" (and thus not a welcome file — which has an entirely different purpose; namely the default file which sould be served when a folder is being requested, which is thus not specifically the root folder), then you should be mapping the servlet on the empty string URL pattern.

<servlet-mapping>
    <servlet-name>index</servlet-name>
    <url-pattern></url-pattern>
</servlet-mapping>

See also Difference between / and /* in servlet mapping url pattern.

How to get all table names from a database?

In your example problem is passed table name pattern in getTables function of DatabaseMetaData.

Some database supports Uppercase identifier, some support lower case identifiers. For example oracle fetches the table name in upper case, while postgreSQL fetch it in lower case.

DatabaseMetaDeta provides a method to determine how the database stores identifiers, can be mixed case, uppercase, lowercase see:http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#storesMixedCaseIdentifiers()

From below example, you can get all tables and view of providing table name pattern, if you want only tables then remove "VIEW" from TYPES array.

public class DBUtility {
    private static final String[] TYPES = {"TABLE", "VIEW"};
    public static void getTableMetadata(Connection jdbcConnection, String tableNamePattern, String schema, String catalog, boolean isQuoted) throws HibernateException {
            try {
                DatabaseMetaData meta = jdbcConnection.getMetaData();
                ResultSet rs = null;
                try {
                    if ( (isQuoted && meta.storesMixedCaseQuotedIdentifiers())) {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    } else if ( (isQuoted && meta.storesUpperCaseQuotedIdentifiers())
                        || (!isQuoted && meta.storesUpperCaseIdentifiers() )) {
                        rs = meta.getTables(
                                StringHelper.toUpperCase(catalog),
                                StringHelper.toUpperCase(schema),
                                StringHelper.toUpperCase(tableNamePattern),
                                TYPES
                            );
                    }
                    else if ( (isQuoted && meta.storesLowerCaseQuotedIdentifiers())
                            || (!isQuoted && meta.storesLowerCaseIdentifiers() )) {
                        rs = meta.getTables( 
                                StringHelper.toLowerCase( catalog ),
                                StringHelper.toLowerCase(schema), 
                                StringHelper.toLowerCase(tableNamePattern), 
                                TYPES 
                            );
                    }
                    else {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    }

                    while ( rs.next() ) {
                        String tableName = rs.getString("TABLE_NAME");
                        System.out.println("table = " + tableName);
                    }



                }
                finally {
                    if (rs!=null) rs.close();
                }
            }
            catch (SQLException sqlException) {
                // TODO 
                sqlException.printStackTrace();
            }

    }

    public static void main(String[] args) {
        Connection jdbcConnection;
        try {
            jdbcConnection = DriverManager.getConnection("", "", "");
            getTableMetadata(jdbcConnection, "tbl%", null, null, false);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

jQuery changing css class to div

$(document).ready(function () {

            $("#divId").toggleClass('cssclassname'); // toggle class
});

**OR**

$(document).ready(function() {
        $("#objectId").click(function() {  // click or other event to change the div class
                $("#divId").toggleClass("cssclassname");     // toggle class
        )}; 
)};

How to do constructor chaining in C#

You use standard syntax (using this like a method) to pick the overload, inside the class:

class Foo 
{
    private int id;
    private string name;

    public Foo() : this(0, "") 
    {
    }

    public Foo(int id, string name) 
    {
        this.id = id;
        this.name = name;
    }

    public Foo(int id) : this(id, "") 
    {
    }

    public Foo(string name) : this(0, name) 
    {
    }
}

then:

Foo a = new Foo(), b = new Foo(456,"def"), c = new Foo(123), d = new Foo("abc");

Note also:

  • you can chain to constructors on the base-type using base(...)
  • you can put extra code into each constructor
  • the default (if you don't specify anything) is base()

For "why?":

  • code reduction (always a good thing)
  • necessary to call a non-default base-constructor, for example:

    SomeBaseType(int id) : base(id) {...}
    

Note that you can also use object initializers in a similar way, though (without needing to write anything):

SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
         z = new SomeType { DoB = DateTime.Today };

How to calculate a Mod b in Casio fx-991ES calculator

You need 10 ÷R 3 = 1 This will display both the reminder and the quoitent


÷R

enter image description here

How to debug Spring Boot application with Eclipse?

How to debug a remote staging or production Spring Boot application

Server-side

Let's assume you have successfully followed Spring Boot's guide on setting up your Spring Boot application as a service. Your application artifact resides in /srv/my-app/my-app.war, accompanied by a configuration file /srv/my-app/my-app.conf:

# This is file my-app.conf
# What can you do in this .conf file? The my-app.war is prepended with a SysV init.d script
# (yes, take a look into the war file with a text editor). As my-app.war is symlinked in the init.d directory, that init.d script
# gets executed. One of its step is actually `source`ing this .conf file. Therefore we can do anything in this .conf file that
# we can also do in a regular shell script.

JAVA_OPTS="-agentlib:jdwp=transport=dt_socket,address=localhost:8002,server=y,suspend=n"
export SPRING_PROFILES_ACTIVE=staging

When you restart your Spring Boot application with sudo service my-app restart, then in its log file located at /var/log/my-app.log should be a line saying Listening for transport dt_socket at address: 8002.

Client-side (developer machine)

Open an SSH port-forwarding tunnel to the server: ssh -L 8002:localhost:8002 [email protected]. Keep this SSH session running.

In Eclipse, from the toolbar, select Run -> Debug Configurations -> select Remote Java Application -> click the New button -> select as Connection Type Standard (Socket Attach), as Host localhost, and as Port 8002 (or whatever you have configured in the steps before). Click Apply and then Debug.

The Eclipse debugger should now connect to the remote server. Switching to the Debug perspective should show the connected JVM and its threads. Breakpoints should fire as soon as they are remotely triggered.

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

Laravel's Autoload is a bit different:

1) It will in fact use Composer for some stuff

2) It will call Composer with the optimize flag

3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php

4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.

Specifying ssh key in ansible playbook file

If you run your playbook with ansible-playbook -vvv you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).

I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this

# fails
- name: Add all instance public IPs to host group
  add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
  loop: "{{ ec2.instances }}"

but that fails too.

So this is not an answer. Just some debugging help and things not to try.

How can I use a C++ library from node.js?

Try shelljs to call c/c++ program or shared libraries by using node program from linux/unix . node-cmd an option in windows. Both packages basically enable us to call c/c++ program similar to the way we call from terminal/command line.

Eg in ubuntu:

const shell = require('shelljs');

shell.exec("command or script name");

In windows:

const cmd = require('node-cmd');
cmd.run('command here');

Note: shelljs and node-cmd are for running os commands, not specific to c/c++.

C++ variable has initializer but incomplete type?

You cannot define a variable of an incomplete type. You need to bring the whole definition of Cat into scope before you can create the local variable in main. I recommend that you move the definition of the type Cat to a header and include it from the translation unit that has main.

can not find module "@angular/material"

Found this post: "Breaking changes" in angular 9. All modules must be imported separately. Also a fine module available there, thanks to @jeff-gilliland: https://stackoverflow.com/a/60111086/824622

Draw radius around a point in Google map

I have just written a blog article that addresses exactly this, which you may find useful: http://seewah.blogspot.com/2009/10/circle-overlay-on-google-map.html

Basically, you need to create a GGroundOverlay with the correct GLatLngBounds. The tricky bit is in working out the southwest corner coordinate and the northeast corner coordinate of this imaginery square (the GLatLngBounds) bounding this circle, based on the desired radius. The math is quite complicated, but you can just refer to getDestLatLng function in the blog. The rest should be pretty straightforward.

How to Find Item in Dictionary Collection?

Of course, if you want to make sure it's in there otherwise fail then this works:

thisTag = _tags[key];

NOTE: This will fail if the key,value pair does not exists but sometimes that is exactly what you want. This way you can catch it and do something about the error. I would only do this if I am certain that the key,value pair is or should be in the dictionary and if not I want it to know about it via the throw.

Angular cookies

Update: angular2-cookie is now deprecated. Please use my ngx-cookie instead.

Old answer:

Here is angular2-cookie which is the exact implementation of Angular 1 $cookies service (plus a removeAll() method) that I created. It is using the same methods, only implemented in typescript with Angular 2 logic.

You can inject it as a service in the components providers array:

import {CookieService} from 'angular2-cookie/core';

@Component({
    selector: 'my-very-cool-app',
    template: '<h1>My Angular2 App with Cookies</h1>',
    providers: [CookieService]
})

After that, define it in the consturctur as usual and start using:

export class AppComponent { 
  constructor(private _cookieService:CookieService){}

  getCookie(key: string){
    return this._cookieService.get(key);
  }
}

You can get it via npm:

npm install angular2-cookie --save

How can I make git show a list of the files that are being tracked?

The accepted answer only shows files in the current directory's tree. To show all of the tracked files that have been committed (on the current branch), use

git ls-tree --full-tree --name-only -r HEAD
  • --full-tree makes the command run as if you were in the repo's root directory.
  • -r recurses into subdirectories. Combined with --full-tree, this gives you all committed, tracked files.
  • --name-only removes SHA / permission info for when you just want the file paths.
  • HEAD specifies which branch you want the list of tracked, committed files for. You could change this to master or any other branch name, but HEAD is the commit you have checked out right now.

This is the method from the accepted answer to the ~duplicate question https://stackoverflow.com/a/8533413/4880003.

How to take character input in java

Here is the sample program.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadFromConsole {

  public static void main(String[] args) {

    System.out.println("Enter here : ");

    try{
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));

        String value = bufferRead.readLine();

        System.out.println(value);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
  }
}

You can get it easily when you search in Internet. StackExchange recommends to do some research and put some effort before reaching it.

Use <Image> with a local file

This from https://github.com/facebook/react-native/issues/282 worked for me:

adekbadek commented on Nov 11, 2015 It should be mentioned that you don't have to put the images in Images.xcassets - you just put them in the project root and then just require('./myimage.png') as @anback wrote Look at this SO answer and the pull it references

C++ convert hex string to signed integer

I had the same problem today, here's how I solved it so I could keep lexical_cast<>

typedef unsigned int    uint32;
typedef signed int      int32;

class uint32_from_hex   // For use with boost::lexical_cast
{
    uint32 value;
public:
    operator uint32() const { return value; }
    friend std::istream& operator>>( std::istream& in, uint32_from_hex& outValue )
    {
        in >> std::hex >> outValue.value;
    }
};

class int32_from_hex   // For use with boost::lexical_cast
{
    uint32 value;
public:
    operator int32() const { return static_cast<int32>( value ); }
    friend std::istream& operator>>( std::istream& in, int32_from_hex& outValue )
    {
        in >> std::hex >> outvalue.value;
    }
};

uint32 material0 = lexical_cast<uint32_from_hex>( "0x4ad" );
uint32 material1 = lexical_cast<uint32_from_hex>( "4ad" );
uint32 material2 = lexical_cast<uint32>( "1197" );

int32 materialX = lexical_cast<int32_from_hex>( "0xfffefffe" );
int32 materialY = lexical_cast<int32_from_hex>( "fffefffe" );
// etc...

(Found this page when I was looking for a less sucky way :-)

Cheers, A.

Why should the static field be accessed in a static way?

Because when you access a static field, you should do so on the class (or in this case the enum). As in

MyUnits.MILLISECONDS;

Not on an instance as in

m.MILLISECONDS;

Edit To address the question of why: In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.

exception in initializer error in java when using Netbeans

@Christian Ullenboom' explanation is correct.

I'm surmising that the OBD2nerForm code you posted is a static initializer block and that it is all generated. Based on that and on the stack trace, it seems likely that generated code is tripping up because it has found some component of your form that doesn't have the type that it is expecting.

I'd do the following to try and diagnose this:

  • Google for reports of similar problems with NetBeans generated forms.
  • If you are running an old version of NetBeans, scan through the "bugs fixed" pages for more recent releases. Or just upgrade try a newer release anyway to see if that fixes the problem.
  • Try cutting bits out of the form design until the problem "goes away" ... and try to figure out what the real cause is that way.
  • Run the application under a debugger to figure out what is being (incorrectly) type cast as what. Just knowing the class names may help. And looking at the instance variables of the objects may reveal more; e.g. which specific form component is causing the problem.

My suspicion is that the root cause is a combination of something a bit unusual (or incorrect) with your form design, and bugs in the NetBeans form generator that is not coping with your form. If you can figure it out, a workaround may reveal itself.

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

Update to Tomcat 7.0.58 (or newer).

See: https://bz.apache.org/bugzilla/show_bug.cgi?id=57173#c16

The performance improvement that triggered this regression has been reverted from from trunk, 8.0.x (for 8.0.16 onwards) and 7.0.x (for 7.0.58 onwards) and will not be reapplied.

How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?

If you have Cygwin installed (which I strongly recommend for a variety of reasons), you could use the 'file' utility on the DLL

file <filename>

which would give an output like this:

icuuc36.dll: MS-DOS executable PE  for MS Windows (DLL) (GUI) Intel 80386 32-bit

Is there a way to call a stored procedure with Dapper?

Same from above, bit more detailed

Using .Net Core

Controller

public class TestController : Controller
{
    private string connectionString;

    public IDbConnection Connection
    {
        get { return new SqlConnection(connectionString); }
    }

    public TestController()
    {
        connectionString = @"Data Source=OCIUZWORKSPC;Initial Catalog=SocialStoriesDB;Integrated Security=True";
    }

    public JsonResult GetEventCategory(string q)
    {
        using (IDbConnection dbConnection = Connection)
        {
            var categories = dbConnection.Query<ResultTokenInput>("GetEventCategories", new { keyword = q },
    commandType: CommandType.StoredProcedure).FirstOrDefault();

            return Json(categories);
        }
    }

    public class ResultTokenInput
    {
        public int ID { get; set; }
        public string name { get; set; }            
    }
}

Stored Procedure ( parent child relation )

create PROCEDURE GetEventCategories
@keyword as nvarchar(100)
AS
    BEGIN

    WITH CTE(Id, Name, IdHierarchy,parentId) AS
    (
      SELECT 
        e.EventCategoryID as Id, cast(e.Title as varchar(max)) as Name,
        cast(cast(e.EventCategoryID as char(5)) as varchar(max)) IdHierarchy,ParentID
      FROM 
        EventCategory e  where e.Title like '%'+@keyword+'%'
     -- WHERE 
      --  parentid = @parentid

      UNION ALL

      SELECT 
        p.EventCategoryID as Id, cast(p.Title + '>>' + c.name as varchar(max)) as Name,
        c.IdHierarchy + cast(p.EventCategoryID as char(5)),p.ParentID
      FROM 
        EventCategory p 
      JOIN  CTE c ON c.Id = p.parentid

        where p.Title like '%'+@keyword+'%'
    )
    SELECT 
      * 
    FROM 
      CTE
    ORDER BY 
      IdHierarchy

References in case

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using SocialStoriesCore.Data;
using Microsoft.EntityFrameworkCore;
using Dapper;
using System.Data;
using System.Data.SqlClient;

What is the Record type in typescript?

A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.

For example, say I have a Union like this:

type CatNames = "miffy" | "boris" | "mordred";

Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.

type CatList = Record<CatNames, {age: number}>

If I want to satisfy this CatList, I must create an object like this:

const cats:CatList = {
  miffy: { age:99 },
  boris: { age:16 },
  mordred: { age:600 }
}

You get very strong type safety:

  • If I forget a cat, I get an error.
  • If I add a cat that's not allowed, I get an error.
  • If I later change CatNames, I get an error. This is especially useful because CatNames is likely imported from another file, and likely used in many places.

Real-world React example.

I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes

I had a union like this:

type Statuses = "failed" | "complete";

I used this to create an object like this:

const icons: Record<
  Statuses,
  { iconType: IconTypes; iconColor: IconColors }
> = {
  failed: {
    iconType: "warning",
    iconColor: "red"
  },
  complete: {
    iconType: "check",
    iconColor: "green"
  };

I could then render by destructuring an element from the object into props, like so:

const Status = ({status}) => <Icon {...icons[status]} />

If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.

Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.

"echo -n" prints "-n"

Just for the most popular linux Ubuntu & it's bash:

  1. Check which shell are you using? Mostly below works, else see this:

    echo $0

  2. If above prints bash, then below will work:

    printf "hello with no new line printed at end"
    OR
    echo -n "hello with no new line printed at end"

How to trim white spaces of array values in php

function trimArray(&$value) 
{ 
    $value = trim($value); 
}
$pmcArray = array('php ','mysql ', ' code ');
array_walk($pmcArray, 'trimArray');

by using array_walk function, we can remove space from array elements and elements return the result in same array.

How to query data out of the box using Spring data JPA by both Sort and Pageable?

There are two ways to achieve this:

final PageRequest page1 = new PageRequest(
  0, 20, Direction.ASC, "lastName", "salary"
);

final PageRequest page2 = new PageRequest(
  0, 20, new Sort(
    new Order(Direction.ASC, "lastName"), 
    new Order(Direction.DESC, "salary")
  )
);

dao.findAll(page1);

As you can see the second form is more flexible as it allows to define different direction for every property (lastName ASC, salary DESC).

IE Enable/Disable Proxy Settings via Registry

modifying the proxy value under

[HKEY_USERS\<your SID>\Software\Microsoft\Windows\CurrentVersion\Internet Settings]

doesnt need to restart ie

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

Where can I find "make" program for Mac OS X Lion?

You need to install Xcode from App Store.

Then start Xcode, go to Xcode->Preferences->Downloads and install component named "Command Line Tools". After that all the relevant tools will be placed in /usr/bin folder and you will be able to use it just as it was in 10.6.

how to prevent adding duplicate keys to a javascript array

You can try this:

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});

Easiest way to find duplicate values in a JavaScript array

Operator overloading in Java

As many others have answered: Java doesn't support user-defined operator overloading.

Maybe this is off-topic, but I want to comment on some things I read in some answers.

About readability.
Compare:

  1. c = a + b
  2. c = a.add(b)

Look again!
Which one is more readable?

A programming language that allows the creation of user-defined types, should allow them to act in the same way as the built-in types (or primitive types).

So Java breaks a fundamental principle of Generic Programming:
We should be able to interchange objects of built-in types with objects of user-defined types.
(You may be wondering: "Did he say 'objects of built-in'?". Yes, see here.)

About String concatenation:

Mathematicians use the symbol + for commutative operations on sets.
So we can be sure that a + b = b + a.
String concatenation (in most programming languages) doesn't respect this common mathematical notation.

a := "hello";
b := "world";
c := (a + b = b + a);

or in Java:

String a = "hello";
String b = "world";
boolean c = (a + b).equals(b + a);

Extra:
Notice how in Java equality and identity are confused. The == (equality) symbol means:
a. Equality for primitive types.
b. Identity-check for user-defined types, therefore, we are forced to use the function equals() for equality.
But... What has this to do with operator overloading?
If the language allows the operator overloading the user could give the proper meaning to the equality operator.

Move textfield when keyboard appears swift

For moving your view while editing textfield try this , I have applied this ,

Option 1 :- ** **Update in Swift 5.0 and iPhone X , XR , XS and XS Max Move using NotificationCenter

  • Register this Notification in func viewWillAppear(_ animated: Bool)

  • Deregister this Notification in func viewWillDisappear(_ animated: Bool)

Note:- If you will not deregister than it will call from child class and will reason of crashing or else.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow(notification:)), name:  UIResponder.keyboardWillShowNotification, object: nil )
}
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
}

@objc func keyboardWillShow( notification: Notification) {
    if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
        var newHeight: CGFloat
        let duration:TimeInterval = (notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
        let animationCurveRawNSN = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
        let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
        let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)
        if #available(iOS 11.0, *) {
            newHeight = keyboardFrame.cgRectValue.height - self.view.safeAreaInsets.bottom
        } else {
            newHeight = keyboardFrame.cgRectValue.height
        }
        let keyboardHeight = newHeight  + 10 // **10 is bottom margin of View**  and **this newHeight will be keyboard height**
        UIView.animate(withDuration: duration,
                       delay: TimeInterval(0),
                       options: animationCurve,
                       animations: {
                        self.view.textViewBottomConstraint.constant = keyboardHeight **//Here you can manage your view constraints for animated show**
                        self.view.layoutIfNeeded() },
                       completion: nil)
    }
}

Option 2 :- Its work fine

func textFieldDidBeginEditing(textField: UITextField) {
        self.animateViewMoving(up: true, moveValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
        self.animateViewMoving(up: false, moveValue: 100)
}

func animateViewMoving (up:Bool, moveValue :CGFloat){
    var movementDuration:NSTimeInterval = 0.3
    var movement:CGFloat = ( up ? -moveValue : moveValue)
    UIView.beginAnimations( "animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration )
    self.view.frame = CGRectOffset(self.view.frame, 0,  movement)
    UIView.commitAnimations()
}

I got this answer from this source UITextField move up when keyboard appears in Swift

IN the Swift 4 ---

func textFieldDidBeginEditing(_ textField: UITextField) {
        animateViewMoving(up: true, moveValue: 100)
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        animateViewMoving(up: false, moveValue: 100)
    }
    func animateViewMoving (up:Bool, moveValue :CGFloat){
        let movementDuration:TimeInterval = 0.3
        let movement:CGFloat = ( up ? -moveValue : moveValue)
        UIView.beginAnimations( "animateView", context: nil)
        UIView.setAnimationBeginsFromCurrentState(true)
        UIView.setAnimationDuration(movementDuration ) 
        self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
        UIView.commitAnimations()
    }

Android WebView Cookie Problem

Solution:Webview CookieSyncManager

CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.setCookie("http://xx.example.com","mid="+MySession.GetSession().sessionId+" ; Domain=.example.com");
cookieSyncManager.sync();

String cookie = cookieManager.getCookie("http://xx.example.com");

Log.d(LOGTAG, "cookie ------>"+cookie);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new TuWebViewClient());
mWebView.loadUrl("http://xx.example.com");

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

I want to add something on @Michael Laffargue's post:

jqXHR.done() is faster!

jqXHR.success() have some load time in callback and sometimes can overkill script. I find that on hard way before.

UPDATE:

Using jqXHR.done(), jqXHR.fail() and jqXHR.always() you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:

/* Initialize some your AJAX function */
function call_ajax(attr){
    var settings=$.extend({
        call            : 'users',
        option          : 'list'
    }, attr );

    return $.ajax({
        type: "POST",
        url: "//exapmple.com//ajax.php",
        data: settings,
        cache : false
    });
}

/* .... Somewhere in your code ..... */

call_ajax({
    /* ... */
    id : 10,
    option : 'edit_user'
    change : {
          name : 'John Doe'
    }
    /* ... */
}).done(function(data){

    /* DO SOMETHING AWESOME */

});

Right to Left support for Twitter Bootstrap 3

you can use my project i create bootstrap 3 rtl with sass and gulp so you can easely customize it https://github.com/z-avanes/bootstrap3-rtl

What is a void pointer in C++?

A void* does not mean anything. It is a pointer, but the type that it points to is not known.

It's not that it can return "anything". A function that returns a void* generally is doing one of the following:

  • It is dealing in unformatted memory. This is what operator new and malloc return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE: void.
  • It is an opaque handle; it references a created object without naming a specific type. Code that does this is generally poorly formed, since this is better done by forward declaring a struct/class and simply not providing a public definition for it. Because then, at least it has a real type.
  • It returns a pointer to storage that contains an object of a known type. However, that API is used to deal with objects of a wide variety of types, so the exact type that a particular call returns cannot be known at compile time. Therefore, there will be some documentation explaining when it stores which kinds of objects, and therefore which type you can safely cast it to.

This construct is nothing like dynamic or object in C#. Those tools actually know what the original type is; void* does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong, and there's no way to ask if a particular usage is the right one.

And on a personal note, if you see code that uses void*'s "often", you should rethink what code you're looking at. void* usage, especially in C++, should be rare, used primary for dealing in raw memory.

Difference between Divide and Conquer Algo and Dynamic Programming

  • Divide and Conquer
    • They broke into non-overlapping sub-problems
    • Example: factorial numbers i.e. fact(n) = n*fact(n-1)
fact(5) = 5* fact(4) = 5 * (4 * fact(3))= 5 * 4 * (3 *fact(2))= 5 * 4 * 3 * 2 * (fact(1))

As we can see above, no fact(x) is repeated so factorial has non overlapping problems.

  • Dynamic Programming
    • They Broke into overlapping sub-problems
    • Example: Fibonacci numbers i.e. fib(n) = fib(n-1) + fib(n-2)
fib(5) = fib(4) + fib(3) = (fib(3)+fib(2)) + (fib(2)+fib(1))

As we can see above, fib(4) and fib(3) both use fib(2). similarly so many fib(x) gets repeated. that's why Fibonacci has overlapping sub-problems.

  • As a result of the repetition of sub-problem in DP, we can keep such results in a table and save computation effort. this is called as memoization

Pytorch reshape tensor dimension

import torch
t = torch.ones((2, 3, 4))
t.size()
>>torch.Size([2, 3, 4])
a = t.view(-1,t.size()[1]*t.size()[2])
a.size()
>>torch.Size([2, 12])

adding 30 minutes to datetime php/mysql

Try this one

DATE_ADD(datefield, INTERVAL 30 MINUTE)

SQL Server: Is it possible to insert into two tables at the same time?

If you want the actions to be more or less atomic, I would make sure to wrap them in a transaction. That way you can be sure both happened or both didn't happen as needed.

Detect Close windows event by jQuery

You can solve this problem with vanilla-Js:

Unload Basics

If you want to prompt or warn your user that they're going to close your page, you need to add code that sets .returnValue on a beforeunload event:

    window.addEventListener('beforeunload', (event) => {
      event.returnValue = `Are you sure you want to leave?`;
    });

There's two things to remember.

  1. Most modern browsers (Chrome 51+, Safari 9.1+ etc) will ignore what you say and just present a generic message. This prevents webpage authors from writing egregious messages, e.g., "Closing this tab will make your computer EXPLODE! ".

  2. Showing a prompt isn't guaranteed. Just like playing audio on the web, browsers can ignore your request if a user hasn't interacted with your page. As a user, imagine opening and closing a tab that you never switch to—the background tab should not be able to prompt you that it's closing.

Optionally Show

You can add a simple condition to control whether to prompt your user by checking something within the event handler. This is fairly basic good practice, and could work well if you're just trying to warn a user that they've not finished filling out a single static form. For example:

    let formChanged = false;
    myForm.addEventListener('change', () => formChanged = true);
    window.addEventListener('beforeunload', (event) => {
      if (formChanged) {
        event.returnValue = 'You have unfinished changes!';
      }
    });

But if your webpage or webapp is reasonably complex, these kinds of checks can get unwieldy. Sure, you can add more and more checks, but a good abstraction layer can help you and have other benefits—which I'll get to later. ???


Promises

So, let's build an abstraction layer around the Promise object, which represents the future result of work- like a response from a network fetch().

The traditional way folks are taught promises is to think of them as a single operation, perhaps requiring several steps- fetch from the server, update the DOM, save to a database. However, by sharing the Promise, other code can leverage it to watch when it's finished.

Pending Work

Here's an example of keeping track of pending work. By calling addToPendingWork with a Promise—for example, one returned from fetch()—we'll control whether to warn the user that they're going to unload your page.

    const pendingOps = new Set();

    window.addEventListener('beforeunload', (event) => {
      if (pendingOps.size) {
        event.returnValue = 'There is pending work. Sure you want to leave?';
      }
    });

    function addToPendingWork(promise) {
      pendingOps.add(promise);
      const cleanup = () => pendingOps.delete(promise);
      promise.then(cleanup).catch(cleanup);
    }

Now, all you need to do is call addToPendingWork(p) on a promise, maybe one returned from fetch(). This works well for network operations and such- they naturally return a Promise because you're blocked on something outside the webpage's control.

more detail can view in this url:

https://dev.to/chromiumdev/sure-you-want-to-leavebrowser-beforeunload-event-4eg5

Hope that can solve your problem.

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

Html.Label - Just creates a label tag with whatever the string passed into the constructor is

Html.LabelFor - Creates a label for that specific property. This is strongly typed. By default, this will just do the name of the property (in the below example, it'll output MyProperty if that Display attribute wasn't there). Another benefit of this is you can set the display property in your model and that's what will be put here:

public class MyModel
{
    [Display(Name="My property title")
    public class MyProperty{get;set;}
}

In your view:

Html.LabelFor(x => x.MyProperty) //Outputs My property title

In the above, LabelFor will display <label for="MyProperty">My property title</label>. This works nicely so you can define in one place what the label for that property will be and have it show everywhere.

How to get all count of mongoose model?

The collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead.

userModel.countDocuments(query).exec((err, count) => {
    if (err) {
        res.send(err);
        return;
    }

    res.json({ count: count });
});

Onclick event to remove default value in a text input field

<input name="Name" value="Enter Your Name" onfocus="freez(this)" onblur="freez(this)">


function freez(obj)
{
 if(obj.value=='')
 {
   obj.value='Enter Your Name';
 }else if(obj.value=='Enter Your Name')
 {
   obj.value='';
 }
} 

Create a HTML table where each TR is a FORM

If all of these rows are related and you need to alter the tabular data ... why not just wrap the entire table in a form, and change GET to POST (unless you know that you're not going to be sending more than the max amount of data a GET request can send).

(That's assuming, of course, that all of the data is going to the same place.)

<form method="POST" action="your_action">
<table>
<tr>
<td><input type="text" name="r1c1" value="" /></td>
<!-- ... snip ... -->
</tr>
<!-- ... repeat as needed ... -->
</table>
</form>

How can I use jQuery to move a div across the screen

You will want to check out the jQuery animate() feature. The standard way of doing this is positioning an element absolutely and then animating the "left" or "right" CSS property. An equally popular way is to increase/decrease the left or right margin.

Now, having said this, you need to be aware of severe performance loss for any type of animation that lasts longer than a second or two. Javascript was simply not meant to handle long, sustained, slow animations. This has to do with the way the DOM element is redrawn and recalculated for each "frame" of the animation. If you're doing a page-width animation that lasts more than a couple seconds, expect to see your processor spike by 50% or more. If you're on IE6, prepare to see your computer spontaneously combust into a flaming ball of browser incompetence.

To read up on this, check out this thread (from my very first Stackoverflow post no less)!

Here's a link to the jQuery docs for the animate() feature: http://docs.jquery.com/Effects/animate

How to set a border for an HTML div tag

You need to set more fields then just border-width. The style basically puts the border on the page. Width controls the thickness, and color tells it what color to make the border.

border-style: solid; border-width:thin; border-color: #FFFFFF;

How do I paste multi-line bash codes into terminal and run it all at once?

iTerm handles multiple-line command perfectly, it saves multiple-lines command as one command, then we can use Cmd+ Shift + ; to navigate the history.

Check more iTerm tips at Working effectively with iTerm

Execute script after specific delay using JavaScript

why can't you put the code behind a promise? (typed in off the top of my head)

_x000D_
_x000D_
new Promise(function(resolve, reject) {_x000D_
  setTimeout(resolve, 2000);_x000D_
}).then(function() {_x000D_
  console.log('do whatever you wanted to hold off on');_x000D_
});
_x000D_
_x000D_
_x000D_

How to use forEach in vueJs?

You can also use .map() as:

var list=[];

response.data.message.map(function(value, key) {
     list.push(value);
   });

How can I build multiple submit buttons django form?

Eg:

if 'newsletter_sub' in request.POST:
    # do subscribe
elif 'newsletter_unsub' in request.POST:
    # do unsubscribe

How to suppress binary file matching results in grep

This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:

bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk  ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$

How to delete an app from iTunesConnect / App Store Connect

As the instructions state on the iTuneconnect Developer Guidelines you need to ensure that you are the "team agent" to delete apps. This is stated in the quote below from the developer guidelines.

If the Delete App button isn’t displayed, check that you’re the team agent and that the app is in one of the statuses that allow the app to be deleted.

I have just checked on my account by logging in as the main account holder and the delete button is there for an app that I have previously removed from sale but when I have looked in as another user they don't have this permission, only the main account holder seems to have it.

Find if a textbox is disabled or not using jquery

You can check if a element is disabled or not with this:

if($("#slcCausaRechazo").prop('disabled') == false)
{
//your code to realice 
}

How can I get javascript to read from a .json file?

Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.

$.ajax({
    url: "File.json", //the path of the file is replaced by File.json
    dataType: "json",
    success: function (response) {
        console.log(response); //it will return the json array
    }
});

efficient way to implement paging

In 2008 we cant use Skip().Take()

The way is:

var MinPageRank = (PageNumber - 1) * NumInPage + 1
var MaxPageRank = PageNumber * NumInPage

var visit = Visita.FromSql($"SELECT * FROM (SELECT [RANK] = ROW_NUMBER() OVER (ORDER BY Hora DESC),* FROM Visita WHERE ) A WHERE A.[RANK] BETWEEN {MinPageRank} AND {MaxPageRank}").ToList();

Resetting MySQL Root Password with XAMPP on Localhost

You want to edit this file: "\xampp\phpMyAdmin\config.inc.php"

change this line:

$cfg['Servers'][$i]['password'] = 'WhateverPassword';

to whatever your password is. If you don't remember your password, then run this command within the Shell:

mysqladmin.exe -u root password WhateverPassword

where WhateverPassword is your new password.

How do I remove a library from the arduino environment?

Quote from official documentation as of August 2013:

User-created libraries as of version 0017 go in a subdirectory of your default sketch directory. For example, on OSX, the new directory would be ~/Documents/Arduino/libraries/. On Windows, it would be My Documents\Arduino\libraries\. To add your own library, create a new directory in the libraries directory with the name of your library. The folder should contain a C or C++ file with your code and a header file with your function and variable declarations. It will then appear in the Sketch | Import Library menu in the Arduino IDE.

To remove a library, stop the Arduino IDE and remove the library directory from the aforementioned location.

What's the best visual merge tool for Git?

IntelliJ IDEA has a sophisticated merge conflict resolution tool with the Resolve magic wand, which greatly simplifies merging:

Source: https://blog.jetbrains.com/dotnet/2017/03/13/rider-eap-update-version-control-database-editor-improvements/

Can't compare naive and aware datetime.now() <= challenge.datetime_end

datetime.datetime.now is not timezone aware.

Django comes with a helper for this, which requires pytz

from django.utils import timezone
now = timezone.now()

You should be able to compare now to challenge.datetime_start

How to escape a JSON string containing newline characters using JavaScript?

Looks like this is an ancient post really :-) But guys, the best workaround I have for this, to be 100% that it works without complicated code, is to use both functions of encoding/decoding to base64. These are atob() and btoa(). By far the easiest and best way, no need to worry if you missed any characters to be escaped.

George

Writing image to local server

Cleanest way of saving image locally using request:

const request = require('request');
request('http://link/to/your/image/file.png').pipe(fs.createWriteStream('fileName.png'))

If you need to add authentication token in headers do this:

const request = require('request');
request({
        url: 'http://link/to/your/image/file.png',
        headers: {
            "X-Token-Auth": TOKEN,
        }
    }).pipe(fs.createWriteStream('filename.png'))                    

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

PHP If Statement with Multiple Conditions

I found this method worked for me:

$thisproduct = "my_product_id";
$array=array("$product1", "$product2", "$product3", "$product4");
if (in_array($thisproduct,$array)) {
    echo "Product found";
}

How to catch exception output from Python subprocess.check_output()?

This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):

from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
    cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
    print(e.output.decode()) # print out the stdout messages up to the exception
    print(e) # To print out the exception message

Generate PDF from HTML using pdfMake in Angularjs

I know its not relevant to this post but might help others converting HTML to PDF on client side. This is a simple solution if you use kendo. It also preserves the css (most of the cases).

_x000D_
_x000D_
var generatePDF = function() {_x000D_
  kendo.drawing.drawDOM($("#formConfirmation")).then(function(group) {_x000D_
    kendo.drawing.pdf.saveAs(group, "Converted PDF.pdf");_x000D_
  });_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <!-- Latest compiled and minified CSS -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <!-- Optional theme -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <!-- Latest compiled and minified JavaScript -->_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <script src="//kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <br/>_x000D_
  <button class="btn btn-primary" onclick="generatePDF()"><i class="fa fa-save"></i> Save as PDF</button>_x000D_
  <br/>_x000D_
  <br/>_x000D_
  <div id="formConfirmation">_x000D_
_x000D_
    <div class="container theme-showcase" role="main">_x000D_
      <!-- Main jumbotron for a primary marketing message or call to action -->_x000D_
      <div class="jumbotron">_x000D_
        <h1>Theme example</h1>_x000D_
        <p>This is a template showcasing the optional theme stylesheet included in Bootstrap. Use it as a starting point to create something more unique by building on or modifying it.</p>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Buttons</h1>_x000D_
      </div>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-lg btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-lg btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-lg btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-lg btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-lg btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-lg btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-lg btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-sm btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-sm btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-sm btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-sm btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-sm btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-sm btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-sm btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-xs btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-xs btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-xs btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-xs btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-xs btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-xs btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-xs btn-link">Link</button>_x000D_
      </p>_x000D_
      <div class="page-header">_x000D_
        <h1>Tables</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-md-6">_x000D_
          <table class="table">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-striped">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-bordered">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td rowspan="2">1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@TwBootstrap</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td colspan="2">Larry the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-condensed">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td colspan="2">Larry the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Thumbnails</h1>_x000D_
      </div>_x000D_
      <img data-src="holder.js/200x200" class="img-thumbnail" alt="A generic square placeholder image with a white border around it, making it resemble a photograph taken with an old instant camera">_x000D_
      <div class="page-header">_x000D_
        <h1>Labels</h1>_x000D_
      </div>_x000D_
      <h1>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h1>_x000D_
      <h2>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h2>_x000D_
      <h3>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h3>_x000D_
      <h4>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h4>_x000D_
      <h5>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h5>_x000D_
      <h6>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h6>_x000D_
      <p>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </p>_x000D_
      <div class="page-header">_x000D_
        <h1>Badges</h1>_x000D_
      </div>_x000D_
      <p>_x000D_
        <a href="#">Inbox <span class="badge">42</span></a>_x000D_
      </p>_x000D_
      <ul class="nav nav-pills" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home <span class="badge">42</span></a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages <span class="badge">3</span></a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <div class="page-header">_x000D_
        <h1>Dropdown menus</h1>_x000D_
      </div>_x000D_
      <div class="dropdown theme-dropdown clearfix">_x000D_
        <a id="dropdownMenu1" href="#" class="sr-only dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">_x000D_
          <li class="active"><a href="#">Action</a>_x000D_
          </li>_x000D_
          <li><a href="#">Another action</a>_x000D_
          </li>_x000D_
          <li><a href="#">Something else here</a>_x000D_
          </li>_x000D_
          <li role="separator" class="divider"></li>_x000D_
          <li><a href="#">Separated link</a>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Navs</h1>_x000D_
      </div>_x000D_
      <ul class="nav nav-tabs" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <ul class="nav nav-pills" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <div class="page-header">_x000D_
        <h1>Navbars</h1>_x000D_
      </div>_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">Project name</a>_x000D_
          </div>_x000D_
          <div class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="#">Home</a>_x000D_
              </li>_x000D_
              <li><a href="#about">About</a>_x000D_
              </li>_x000D_
              <li><a href="#contact">Contact</a>_x000D_
              </li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="#">Action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Another action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Something else here</a>_x000D_
                  </li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li class="dropdown-header">Nav header</li>_x000D_
                  <li><a href="#">Separated link</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">One more separated link</a>_x000D_
                  </li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
          </div>_x000D_
          <!--/.nav-collapse -->_x000D_
        </div>_x000D_
      </nav>_x000D_
      <nav class="navbar navbar-inverse">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">Project name</a>_x000D_
          </div>_x000D_
          <div class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="#">Home</a>_x000D_
              </li>_x000D_
              <li><a href="#about">About</a>_x000D_
              </li>_x000D_
              <li><a href="#contact">Contact</a>_x000D_
              </li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="#">Action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Another action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Something else here</a>_x000D_
                  </li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li class="dropdown-header">Nav header</li>_x000D_
                  <li><a href="#">Separated link</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">One more separated link</a>_x000D_
                  </li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
          </div>_x000D_
          <!--/.nav-collapse -->_x000D_
        </div>_x000D_
      </nav>_x000D_
      <div class="page-header">_x000D_
        <h1>Alerts</h1>_x000D_
      </div>_x000D_
      <div class="alert alert-success" role="alert">_x000D_
        <strong>Well done!</strong> You successfully read this important alert message._x000D_
      </div>_x000D_
      <div class="alert alert-info" role="alert">_x000D_
        <strong>Heads up!</strong> This alert needs your attention, but it's not super important._x000D_
      </div>_x000D_
      <div class="alert alert-warning" role="alert">_x000D_
        <strong>Warning!</strong> Best check yo self, you're not looking too good._x000D_
      </div>_x000D_
      <div class="alert alert-danger" role="alert">_x000D_
        <strong>Oh snap!</strong> Change a few things up and try submitting again._x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Progress bars</h1>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"><span class="sr-only">60% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"><span class="sr-only">40% Complete (success)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"><span class="sr-only">20% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete (warning)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"><span class="sr-only">80% Complete (danger)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-success" style="width: 35%"><span class="sr-only">35% Complete (success)</span>_x000D_
        </div>_x000D_
        <div class="progress-bar progress-bar-warning" style="width: 20%"><span class="sr-only">20% Complete (warning)</span>_x000D_
        </div>_x000D_
        <div class="progress-bar progress-bar-danger" style="width: 10%"><span class="sr-only">10% Complete (danger)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>List groups</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-sm-4">_x000D_
          <ul class="list-group">_x000D_
            <li class="list-group-item">Cras justo odio</li>_x000D_
            <li class="list-group-item">Dapibus ac facilisis in</li>_x000D_
            <li class="list-group-item">Morbi leo risus</li>_x000D_
            <li class="list-group-item">Porta ac consectetur ac</li>_x000D_
            <li class="list-group-item">Vestibulum at eros</li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="list-group">_x000D_
            <a href="#" class="list-group-item active">_x000D_
              Cras justo odio_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">Dapibus ac facilisis in</a>_x000D_
            <a href="#" class="list-group-item">Morbi leo risus</a>_x000D_
            <a href="#" class="list-group-item">Porta ac consectetur ac</a>_x000D_
            <a href="#" class="list-group-item">Vestibulum at eros</a>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="list-group">_x000D_
            <a href="#" class="list-group-item active">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Panels</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-default">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-primary">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-success">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-info">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-warning">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-danger">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
      </div>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to add an event after close the modal window?

If you're using version 3.x of Bootstrap, the correct way to do this now is:

$('#myModal').on('hidden.bs.modal', function (e) {
  // do something...
})

Scroll down to the events section to learn more.

http://getbootstrap.com/javascript/#modals-usage

This appears to remain unchanged for whenever version 4 releases (http://v4-alpha.getbootstrap.com/components/modal/#events), but if it does I'll be sure to update this post with the relevant information.

jQuery removing '-' character from string

$mylabel.text( $mylabel.text().replace('-', '') );

Since text() gets the value, and text( "someValue" ) sets the value, you just place one inside the other.

Would be the equivalent of doing:

var newValue = $mylabel.text().replace('-', '');
$mylabel.text( newValue );

EDIT:

I hope I understood the question correctly. I'm assuming $mylabel is referencing a DOM element in a jQuery object, and the string is in the content of the element.

If the string is in some other variable not part of the DOM, then you would likely want to call the .replace() function against that variable before you insert it into the DOM.

Like this:

var someVariable = "-123456";
$mylabel.text( someVariable.replace('-', '') );

or a more verbose version:

var someVariable = "-123456";
someVariable = someVariable.replace('-', '');
$mylabel.text( someVariable );

How can I render a list select box (dropdown) with bootstrap?

Another option is to make the Bootstrap dropdown behave like a select using jQuery...

$(".dropdown-menu li a").click(function(){
  var selText = $(this).text();
  $(this).parents('.btn-group').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');
});

http://www.bootply.com/b4NKREUPkN

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

If you see those characters you probably just didn’t specify the character encoding properly. Because those characters are the result when an UTF-8 multi-byte string is interpreted with a single-byte encoding like ISO 8859-1 or Windows-1252.

In this case ë could be encoded with 0xC3 0xAB that represents the Unicode character ë (U+00EB) in UTF-8.

How to set a Javascript object values dynamically?

You can get the property the same way as you set it.

foo = {
 bar: "value"
}

You set the value foo["bar"] = "baz";

To get the value foo["bar"]

will return "baz".

setImmediate vs. nextTick

I recommend you to check docs section dedicated for Loop to get better understanding. Some snippet taken from there:

We have two calls that are similar as far as users are concerned, but their names are confusing.

  • process.nextTick() fires immediately on the same phase

  • setImmediate() fires on the following iteration or 'tick' of the
    event loop

In essence, the names should be swapped. process.nextTick() fires more immediately than setImmediate(), but this is an artifact of the past which is unlikely to change.

Looping over arrays, printing both index and value

In bash 4, you can use associative arrays:

declare -A foo
foo[0]="bar"
foo[35]="baz"
for key in "${!foo[@]}"
do
    echo "key: $key, value: ${foo[$key]}"
done

# output
# $ key: 0, value bar.
# $ key: 35, value baz.

In bash 3, this works (also works in zsh):

map=( )
map+=("0:bar")
map+=("35:baz")

for keyvalue in "${map[@]}" ; do
    key=${keyvalue%%:*}
    value=${keyvalue#*:}
    echo "key: $key, value $value."
done

What jar should I include to use javax.persistence package in a hibernate based application?

For JPA 2.1 the javax.persistence package can be found in here:

<dependency>
   <groupId>org.hibernate.javax.persistence</groupId>
   <artifactId>hibernate-jpa-2.1-api</artifactId>
   <version>1.0.0.Final</version>
</dependency>

See: hibernate-jpa-2.1-api on Maven Central The pattern seems to be to change the artefact name as the JPA version changes. If this continues new versions can be expected to arrive in Maven Central here: Hibernate JPA versions

The above JPA 2.1 APi can be used in conjunction with Hibernate 4.3.7, specifically:

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>4.3.7.Final</version>
</dependency>

Best way to remove an event handler in jQuery?

Updated for 2014

Using the latest version of jQuery, you're now able to unbind all events on a namespace by simply doing $( "#foo" ).off( ".myNamespace" );

"Invalid form control" only in Google Chrome

I had the error:

An invalid form control with name='telefono' is not focusable.

This was happening because I was not using the required field correctly, which enabled and disabled when clicking on a checkbok. The solution was to remove the required attribute whenever the checkbok was not marked and mark it as required when the checkbox was marked.

var telefono = document.getElementById("telefono");  
telefono.removeAttribute("required");

d3 add text to circle

Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.

_x000D_
_x000D_
var width = 960,_x000D_
  height = 500,_x000D_
  json = {_x000D_
    "nodes": [{_x000D_
      "x": 100,_x000D_
      "r": 20,_x000D_
      "label": "Node 1",_x000D_
      "color": "red"_x000D_
    }, {_x000D_
      "x": 200,_x000D_
      "r": 25,_x000D_
      "label": "Node 2",_x000D_
      "color": "blue"_x000D_
    }, {_x000D_
      "x": 300,_x000D_
      "r": 30,_x000D_
      "label": "Node 3",_x000D_
      "color": "green"_x000D_
    }]_x000D_
  };_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
  .attr("width", width)_x000D_
  .attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
  .append("pattern")_x000D_
  .attr({_x000D_
    "id": "stripes",_x000D_
    "width": "8",_x000D_
    "height": "8",_x000D_
    "fill": "red",_x000D_
    "patternUnits": "userSpaceOnUse",_x000D_
    "patternTransform": "rotate(60)"_x000D_
  })_x000D_
  .append("rect")_x000D_
  .attr({_x000D_
    "width": "4",_x000D_
    "height": "8",_x000D_
    "transform": "translate(0,0)",_x000D_
    "fill": "grey"_x000D_
  });_x000D_
_x000D_
function plotChart(json) {_x000D_
  /* Define the data for the circles */_x000D_
  var elem = svg.selectAll("g myCircleText")_x000D_
    .data(json.nodes)_x000D_
_x000D_
  /*Create and place the "blocks" containing the circle and the text */_x000D_
  var elemEnter = elem.enter()_x000D_
    .append("g")_x000D_
    .attr("class", "node-group")_x000D_
    .attr("transform", function(d) {_x000D_
      return "translate(" + d.x + ",80)"_x000D_
    })_x000D_
_x000D_
  /*Create the circle for each block */_x000D_
  var circleInner = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", function(d) {_x000D_
      return d.color;_x000D_
    });_x000D_
_x000D_
  var circleOuter = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", "url(#stripes)");_x000D_
_x000D_
  /* Create the text for each block */_x000D_
  elemEnter.append("text")_x000D_
    .text(function(d) {_x000D_
      return d.label_x000D_
    })_x000D_
    .attr({_x000D_
      "text-anchor": "middle",_x000D_
      "font-size": function(d) {_x000D_
        return d.r / ((d.r * 10) / 100);_x000D_
      },_x000D_
      "dy": function(d) {_x000D_
        return d.r / ((d.r * 25) / 100);_x000D_
      }_x000D_
    });_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
  fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Output:

enter image description here

Below is the link to codepen also:

See the Pen D3-Circle-Pattern-Text by Manish Kumar (@mkdudeja) on CodePen.

Thanks, Manish Kumar

Chrome Fullscreen API

The following test works in Chrome 16 (dev branch) on X86 and Chrome 15 on Mac OSX Lion

http://html5-demos.appspot.com/static/fullscreen.html

Get values from an object in JavaScript

Using lodash _.values(object)

_.values({"id": 1, "second": "abcd"})

[ 1, 'abcd' ]

lodash includes a whole bunch of other functions to work with arrays, objects, collections, strings, and more that you wish were built into JavaScript (and actually seem to slowly be making their way into the language).

What does "export" do in shell programming?

it makes the assignment visible to subprocesses.

$ foo=bar
$ bash -c 'echo $foo'

$ export foo
$ bash -c 'echo $foo'
bar

How to choose the id generation strategy when using JPA and Hibernate


A while ago i wrote a detailed article about Hibernate key generators: http://blog.eyallupu.com/2011/01/hibernatejpa-identity-generators.html

Choosing the correct generator is a complicated task but it is important to try and get it right as soon as possible - a late migration might be a nightmare.

A little off topic but a good chance to raise a point usually overlooked which is sharing keys between applications (via API). Personally I always prefer surrogate keys and if I need to communicate my objects with other systems I don't expose my key (even though it is a surrogate one) – I use an additional ‘external key’. As a consultant I have seen more than once 'great' system integrations using object keys (the 'it is there let's just use it' approach) just to find a year or two later that one side has issues with the key range or something of the kind requiring a deep migration on the system exposing its internal keys. Exposing your key means exposing a fundamental aspect of your code to external constrains shouldn’t really be exposed to.

How to clear the cache in NetBeans

On a Mac with NetBeans 8.1,

  1. NetBeans ? About
  2. Find User Directory path in the About screen
  3. rm -fr 8.1 In your case the version could be different; remove the right version folder.
  4. Reopen NetBeans

Turn off display errors using file "php.ini"

I always use something like this in a configuration file:

// Toggle this to change the setting
define('DEBUG', true);

// You want all errors to be triggered
error_reporting(E_ALL);

if(DEBUG == true)
{
    // You're developing, so you want all errors to be shown
    display_errors(true);

    // Logging is usually overkill during development
    log_errors(false);
}
else
{
    // You don't want to display errors on a production environment
    display_errors(false);

    // You definitely want to log any occurring
    log_errors(true);
}

This allows easy toggling between debug settings. You can improve this further by checking on which server the code is running (development, test, acceptance, and production) and change your settings accordingly.

Note that no errors will be logged if error_reporting is set to 0, as cleverly remarked by Korri.

Count unique values in a column in Excel

You can do the following steps:

  1. First isolate the column (by inserting a blank column before and/or after the column you want to count the unique values if there are any adjacent columns;

  2. Then select the whole column, go to 'Data' > 'Advanced Filter' and check the checkbox 'Unique records only'. This will hide all non-unique records so you can count the unique ones by selecting the whole column.

Check if Python Package is installed

Is there any chance to use the snippets given below? When I run this code, it returns "module pandas is not installed"

a = "pandas"

try:
    import a
    print("module ",a," is installed")
except ModuleNotFoundError:
    print("module ",a," is not installed")

But when I run the code given below:

try:
    import pandas
    print("module is installed")
except ModuleNotFoundError:
    print("module is not installed")

It returns "module pandas is installed".

What is the difference between them?