Programs & Examples On #Lwuit

Lightweight User Interface Toolkit - widget-based UI library for J2ME enabled mobile devices

Command to get time in milliseconds

date command didnt provide milli seconds on OS X, so used an alias from python

millis(){  python -c "import time; print(int(time.time()*1000))"; }

OR

alias millis='python -c "import time; print(int(time.time()*1000))"'

EDIT: following the comment from @CharlesDuffy. Forking any child process takes extra time.

$ time date +%s%N
1597103627N
date +%s%N  0.00s user 0.00s system 63% cpu 0.006 total

Python is still improving it's VM start time, and it is not as fast as ahead-of-time compiled code (such as date).

On my machine, it took about 30ms - 60ms (that is 5x-10x of 6ms taken by date)

$ time python -c "import time; print(int(time.time()*1000))"
1597103899460
python -c "import time; print(int(time.time()*1000))"  0.03s user 0.01s system 83% cpu 0.053 total

I figured awk is lightweight than python, so awk takes in the range of 6ms to 12ms (i.e. 1x to 2x of date):

$ time awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'
1597103729525
awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'  0.00s user 0.00s system 74% cpu 0.010 total

Group By Multiple Columns

Though this question is asking about group by class properties, if you want to group by multiple columns against a ADO object (like a DataTable), you have to assign your "new" items to variables:

EnumerableRowCollection<DataRow> ClientProfiles = CurrentProfiles.AsEnumerable()
                        .Where(x => CheckProfileTypes.Contains(x.Field<object>(ProfileTypeField).ToString()));
// do other stuff, then check for dups...
                    var Dups = ClientProfiles.AsParallel()
                        .GroupBy(x => new { InterfaceID = x.Field<object>(InterfaceField).ToString(), ProfileType = x.Field<object>(ProfileTypeField).ToString() })
                        .Where(z => z.Count() > 1)
                        .Select(z => z);

laravel 5.4 upload image

public function store()
{
    $this->validate(request(), [
        'title' => 'required',
        'slug' => 'required',
        'file' => 'required|image|mimes:jpg,jpeg,png,gif'
    ]);

    $fileName = null;
    if (request()->hasFile('file')) {
        $file = request()->file('file');
        $fileName = md5($file->getClientOriginalName() . time()) . "." . $file->getClientOriginalExtension();
        $file->move('./uploads/categories/', $fileName);    
    }

    Category::create([
        'title' => request()->get('title'),
        'slug' => str_slug(request()->get('slug')),
        'description' => request()->get('description'),
        'category_img' => $fileName,
        'category_status' => 'DEACTIVE'
    ]);

    return redirect()->to('/admin/category');
}

What are major differences between C# and Java?

Another good resource is http://www.javacamp.org/javavscsharp/ This site enumerates many examples that ilustrate almost all the differences between these two programming languages.

About the Attributes, Java has Annotations, that work almost the same way.

how to use XPath with XDocument?

XPath 1.0, which is what MS implements, does not have the idea of a default namespace. So try this:

XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable()); 
xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);

Why does the Visual Studio editor show dots in blank spaces?

go to File -> Preferences -> Settings, this will open two panels side by side, the left one is default setting and the right one is user setting, you can add your setting on right panel, for this you can add "editor.renderWhitespace": "all".

How do I add an existing directory tree to a project in Visual Studio?

You need to put your directory structure in your project directory. And then click "Show All Files" icon in the top of Solution Explorer toolbox. After that, the added directory will be shown up. You will then need to select this directory, right click, and choose "Include in Project."

enter image description here

enter image description here

Is nested function a good approach when required by only one function?

A function inside of a function is commonly used for closures.

(There is a lot of contention over what exactly makes a closure a closure.)

Here's an example using the built-in sum(). It defines start once and uses it from then on:

def sum_partial(start):
    def sum_start(iterable):
        return sum(iterable, start)
    return sum_start

In use:

>>> sum_with_1 = sum_partial(1)
>>> sum_with_3 = sum_partial(3)
>>> 
>>> sum_with_1
<function sum_start at 0x7f3726e70b90>
>>> sum_with_3
<function sum_start at 0x7f3726e70c08>
>>> sum_with_1((1,2,3))
7
>>> sum_with_3((1,2,3))
9

Built-in python closure

functools.partial is an example of a closure.

From the python docs, it's roughly equivalent to:

def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*(args + fargs), **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

(Kudos to @user225312 below for the answer. I find this example easier to figure out, and hopefully will help answer @mango's comment.)

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Follow the steps given below:

  1. Stop your MySQL server completely. This can be done by accessing the Services window inside Windows XP and Windows Server 2003, where you can stop the MySQL service.

  2. Open your MS-DOS command prompt using "cmd" inside the Run window. Inside it navigate to your MySQL bin folder, such as C:\MySQL\bin using the cd command.

  3. Execute the following command in the command prompt: mysqld.exe -u root --skip-grant-tables

  4. Leave the current MS-DOS command prompt as it is, and open a new MS-DOS command prompt window.

  5. Navigate to your MySQL bin folder, such as C:\MySQL\bin using the cd command.

  6. Enter mysql and press enter.

  7. You should now have the MySQL command prompt working. Type use mysql; so that we switch to the "mysql" database.

  8. Execute the following command to update the password:

    UPDATE user SET Password = PASSWORD('NEW_PASSWORD') WHERE User = 'root'; 
    

However, you can now run any SQL command that you wish.

After you are finished close the first command prompt and type exit; in the second command prompt windows to disconnect successfully. You can now start the MySQL service.

vertical-align with Bootstrap 3

This is my solution. Just add this class to your CSS content.

.align-middle {
  display: flex;
  justify-content: center;
  align-items: center;
}

Then your HTML would look like this:

<div class="col-xs-12 align-middle">
  <div class="col-xs-6" style="background-color:blue;">
    <h3>Item</h3>
    <h3>Item</h3>
  </div>
  <div class="col-xs-6" style="background-color:red;">
    <h3>Item</h3>
  </div>
</div>

_x000D_
_x000D_
.align-middle {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}
_x000D_
<html>_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_
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<!DOCTYPE html>_x000D_
    <title>Title</title>_x000D_
  </head>_x000D_
  <body>_x000D_
    <div class="container">_x000D_
      <div class="row">_x000D_
        <div class="col-xs-12 align-middle">_x000D_
          <div class="col-xs-6" style="background-color:blue;">_x000D_
            <h3>Item</h3>_x000D_
            <h3>Item</h3>_x000D_
          </div>_x000D_
          <div class="col-xs-6" style="background-color:red;">_x000D_
            <h3>Item</h3>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What do multiple arrow functions mean in javascript?

Brief and simple

It is a function which returns another function written in short way.

const handleChange = field => e => {
  e.preventDefault()
  // Do something here
}

// is equal to 
function handleChange(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
  }
}

Why people do it ?

Have you faced when you need to write a function which can be customized? Or you have to write a callback function which has fixed parameters (arguments), but you need to pass more variables to the function but avoiding global variables? If your answer "yes" then it is the way how to do it.

For example we have a button with onClick callback. And we need to pass id to the function, but onClick accepts only one parameter event, we can not pass extra parameters within like this:

const handleClick = (event, id) {
  event.preventDefault()
  // Dispatch some delete action by passing record id
}

It will not work!

Therefore we make a function which will return other function with its own scope of variables without any global variables, because global variables are evil .

Below the function handleClick(props.id)} will be called and return a function and it will have id in its scope! No matter how many times it will be pressed the ids will not effect or change each other, they are totally isolated.

const handleClick = id => event {
  event.preventDefault()
  // Dispatch some delete action by passing record id
}

const Confirm = props => (
  <div>
    <h1>Are you sure to delete?</h1>
    <button onClick={handleClick(props.id)}>
      Delete
    </button>
  </div
)

Other benefit

A function which returns another function also called "curried functions" and they are used for function compositions.

You can find example here: https://gist.github.com/sultan99/13ef56b4089789a8d115869ee2c5ec47

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

Either the parameter supplied for ZIP_CODE is larger (in length) than ZIP_CODEs column width or the parameter supplied for CITY is larger (in length) than CITYs column width.

It would be interesting to know the values supplied for the two ? placeholders.

Tests not running in Test Explorer

It is worth mentioning that sometimes NUnit Test Adapter files get corrupted in user folder C:\Users[User]\AppData\Local\Temp\VisualStudioTestExplorerExtensions\NUnit3TestAdapter.3.8.0/build/net35/NUnit3.TestAdapter.dll on Windows 10 and that causes Test Explorer to stop working as it should.

How can I know when an EditText loses focus?

Using Java 8 lambda expression:

editText.setOnFocusChangeListener((v, hasFocus) -> {
    if(!hasFocus) {
        String value = String.valueOf( editText.getText() );
    }        
});

How to change the default background color white to something else in twitter bootstrap

I would not recommend changing the actual bootstrap CSS files. If you do not want to use Jako's first solution you can create a custom bootstrap style sheet with one of the available Bootstrap theme generator (Bootstrap theme generators). That way you can use 1 style sheet with all of the default Bootstrap CSS with just the one change to it that you want. With a Bootstrap theme generator you do not need to write any CSS. You only need to set the hex values for the color you want for the body (Scaffolding; bodyBackground).

What does it mean to bind a multicast (UDP) socket?

To bind a UDP socket when receiving multicast means to specify an address and port from which to receive data (NOT a local interface, as is the case for TCP acceptor bind). The address specified in this case has a filtering role, i.e. the socket will only receive datagrams sent to that multicast address & port, no matter what groups are subsequently joined by the socket. This explains why when binding to INADDR_ANY (0.0.0.0) I received datagrams sent to my multicast group, whereas when binding to any of the local interfaces I did not receive anything, even though the datagrams were being sent on the network to which that interface corresponded.

Quoting from UNIX® Network Programming Volume 1, Third Edition: The Sockets Networking API by W.R Stevens. 21.10. Sending and Receiving

[...] We want the receiving socket to bind the multicast group and port, say 239.255.1.2 port 8888. (Recall that we could just bind the wildcard IP address and port 8888, but binding the multicast address prevents the socket from receiving any other datagrams that might arrive destined for port 8888.) We then want the receiving socket to join the multicast group. The sending socket will send datagrams to this same multicast address and port, say 239.255.1.2 port 8888.

In Laravel, the best way to pass different types of flash messages in the session

If you want to use Bootstrap Alert to make your view more interactive. You can do something like this:

In your function:-

if($author->save()){
    Session::flash('message', 'Author has been successfully added');
    Session::flash('class', 'success'); //you can replace success by [info,warning,danger]
    return redirect('main/successlogin');

In your views:-

@if(Session::has('message'))
    <div class="alert alert-{{Session::get('class')}} alert-dismissible fade show w-50 ml-auto alert-custom"
        role="alert">
        {{ Session::get('message') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

Accessing Websites through a Different Port?

You can use ssh to forward ports onto somewhere else.

If you have two computers, one you browse from, and one which is free to access websites, and is not logged (ie. you own it and it's sitting at home), then you can set up a tunnel between them to forward http traffic over.

For example, I connect to my home computer from work using ssh, with port forwarding, like this:

ssh -L 22222:<target_website>:80 <home_computer>

Then I can point my browser to

http://localhost:22222/

And this request will be forwarded over ssh. Since the work computer is first contacting the home computer, and then contacting the target website, it will be hard to log.

However, this is all getting into 'how to bypass web proxies' and the like, and I suggest you create a new question asking what exactly you want to do.

Ie. "How do I bypass web proxies to avoid my traffic being logged?"

How do I pass a unique_ptr argument to a constructor or a function?

Base(Base::UPtr n):next(std::move(n)) {}

should be much better as

Base(Base::UPtr&& n):next(std::forward<Base::UPtr>(n)) {}

and

void setNext(Base::UPtr n)

should be

void setNext(Base::UPtr&& n)

with same body.

And ... what is evt in handle() ??

How to debug Google Apps Script (aka where does Logger.log log to?)

The dev console will log errors thrown by the app script, so you can just throw an error to get it logged as a normal console.log. It will stop execution, but it might still be useful for step by step debugging.

throw Error('hello world!');

will show up in the console similarly to console.log('hello world')

How do I remove newlines from a text file?

You are missing the most obvious and fast answer especially when you need to do this in GUI in order to fix some weird word-wrap.

  • Open gedit

  • Then Ctrl + H, then put in the Find textbox \n and in Replace with an empty space then fill checkbox Regular expression and voila.

mongodb service is not starting up

Fixed!

The reason was the dbpath variable in /etc/mongodb.conf. Previously, I was using mongodb 1.8, where the default value for dbpath was /data/db. The upstart job mongodb(which comes with mongodb-10gen package) invokes the mongod with --config /etc/mongodb.conf option.

As a solution, I only had to change the owner of the /data/db directory recursively.

Download and open PDF file using Ajax

This snippet is for angular js users which will face the same problem, Note that the response file is downloaded using a programmed click event. In this case , the headers were sent by server containing filename and content/type.

$http({
    method: 'POST', 
    url: 'DownloadAttachment_URL',
    data: { 'fileRef': 'filename.pdf' }, //I'm sending filename as a param
    headers: { 'Authorization': $localStorage.jwt === undefined ? jwt : $localStorage.jwt },
    responseType: 'arraybuffer',
}).success(function (data, status, headers, config) {
    headers = headers();
    var filename = headers['x-filename'];
    var contentType = headers['content-type'];
    var linkElement = document.createElement('a');
    try {
        var blob = new Blob([data], { type: contentType });
        var url = window.URL.createObjectURL(blob);

        linkElement.setAttribute('href', url);
        linkElement.setAttribute("download", filename);

        var clickEvent = new MouseEvent("click", {
            "view": window,
            "bubbles": true,
            "cancelable": false
        });
        linkElement.dispatchEvent(clickEvent);
    } catch (ex) {
        console.log(ex);
    }
}).error(function (data, status, headers, config) {
}).finally(function () {

});

package javax.servlet.http does not exist

The solution that work for is were add the next dependency to my pom.xml file.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
</dependency>

Defining static const integer members in class definition

Here's another way to work around the problem:

std::min(9, int(test::N));

(I think Crazy Eddie's answer correctly describes why the problem exists.)

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

Disable button in WPF?

You could subscribe to the TextChanged event on the TextBox and if the text is empty set the Button to disabled. Or you could bind the Button.IsEnabled property to the TextBox.Text property and use a converter that returns true if there is any text and false otherwise.

Extract subset of key-value pairs from Python dictionary object?

Using map (halfdanrump's answer) is best for me, though haven't timed it...

But if you go for a dictionary, and if you have a big_dict:

  1. Make absolutely certain you loop through the the req. This is crucial, and affects the running time of the algorithm (big O, theta, you name it)
  2. Write it generic enough to avoid errors if keys are not there.

so e.g.:

big_dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w']

{k:big_dict.get(k,None) for k in req )
# or 
{k:big_dict[k] for k in req if k in big_dict)

Note that in the converse case, that the req is big, but my_dict is small, you should loop through my_dict instead.

In general, we are doing an intersection and the complexity of the problem is O(min(len(dict)),min(len(req))). Python's own implementation of intersection considers the size of the two sets, so it seems optimal. Also, being in c and part of the core library, is probably faster than most not optimized python statements. Therefore, a solution that I would consider is:

dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w',...................]

{k:dic[k] for k in set(req).intersection(dict.keys())}

It moves the critical operation inside python's c code and will work for all cases.

golang why don't we have a set datastructure

Another possibility is to use bit sets, for which there is at least one package or you can use the built-in big package. In this case, basically you need to define a way to convert your object to an index.

Creating a button in Android Toolbar

I have added text in ToolBar :

menu_skip.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_settings"
        android:title="@string/text_skip"
        app:showAsAction="never" />
</menu>

MainActivity.java

@Override
boolean onCreateOptionsMenu(Menu menu) {
    inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_otp_skip, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // action with ID action_refresh was selected
        case R.id.menu_item_skip:
            Toast.makeText(this, "Skip selected", Toast.LENGTH_SHORT)
                    .show();
            break;
        default:
            break;
    }
    return true;
}

Take a screenshot via a Python script on Linux

Cross platform solution using wxPython:

import wx
wx.App()  # Need to create an App instance before doing anything
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.EmptyBitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem  # Release bitmap
bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)

How do I edit a file after I shell to a Docker container?

To keep your Docker images small, don't install unnecessary editors. You can edit the files over SSH from the Docker host to the container:

vim scp://remoteuser@containerip//path/to/document

Uncaught SyntaxError: Invalid or unexpected token

I also had an issue with multiline strings in this scenario. @Iman's backtick(`) solution worked great in the modern browsers but caused an invalid character error in Internet Explorer. I had to use the following:

'@item.MultiLineString.Replace(Environment.NewLine, "<br />")'

Then I had to put the carriage returns back again in the js function. Had to use RegEx to handle multiple carriage returns.

// This will work for the following:
// "hello\nworld"
// "hello<br>world"
// "hello<br />world"
$("#MyTextArea").val(multiLineString.replace(/\n|<br\s*\/?>/gi, "\r"));

Does uninstalling a package with "pip" also remove the dependent packages?

No, it doesn't uninstall the dependencies packages. It only removes the specified package:

$ pip install specloud
$ pip freeze # all the packages here are dependencies of specloud package

figleaf==0.6.1
nose==1.1.2
pinocchio==0.3
specloud==0.4.5

$ pip uninstall specloud
$ pip freeze

figleaf==0.6.1
nose==1.1.2
pinocchio==0.3

As you can see those packages are dependencies from specloud and they're still there, but not the specloud package itself.

As mentioned below, You can install and use the pip-autoremove utility to remove a package plus unused dependencies.

How can I exclude all "permission denied" messages from "find"?

Simple answer:

find . > files_and_folders 2>&-

2>&- closes (-) the standard error file descriptor (2) so all error messages are silenced.

  • Exit code will still be 1 if any 'Permission denied' errors would otherwise be printed

Robust answer for GNU find:

find . -type d \! \( -readable -executable \) -prune -print -o -print > files_and_folders

Pass extra options to find that -prune (prevent descending into) but still -print any directory (-typed) that does not (\!) have both -readable and -executable permissions, or (-o) -print any other file.

  • -readable and -executable options are GNU extensions, not part of the POSIX standard
  • May still return 'Permission denied' on abnormal/corrupt files (e.g., see bug report affecting container-mounted filesystems using lxcfs < v2.0.5)

Robust answer that works with any POSIX-compatible find (GNU, OSX/BSD, etc)

{ LC_ALL=C find . 3>&2 2>&1 1>&3 > files_and_folders | grep -v 'Permission denied'; [ $? = 1 ]; } 3>&2 2>&1

Use a pipeline to pass the standard error stream to grep, removing all lines containing the 'Permission denied' string.

LC_ALL=C sets the POSIX locale using an environment variable, 3>&2 2>&1 1>&3 and 3>&2 2>&1 duplicate file descriptors to pipe the standard-error stream to grep, and [ $? = 1 ] uses [] to invert the error code returned by grep to approximate the original behavior of find.

  • Will also filter any 'Permission denied' errors due to output redirection (e.g., if the files_and_folders file itself is not writable)

How to fix '.' is not an internal or external command error

Replacing forward(/) slash with backward(\) slash will do the job. The folder separator in Windows is \ not /

Can JavaScript connect with MySQL?

I understood your question I think you are confusing it with languages like dot.net and java where you can open DB connection within your code. No, JavaScript can not directly connect to MySQL as JavaScript is a client side scripting language(Exception Node.js).You need a middle layer like RESTful API to access data.

How to access my localhost from another PC in LAN?

IP can be any LAN or WAN IP address. But you'll want to set your firewall connection allow it.

Device connection with webserver pc can be by LAN or WAN (i.e by wifi, connectify, adhoc, cable, mypublic wifi etc)

You should follow these steps:

  1. Go to the control panel
  2. Inbound rules > new rules
  3. Click port > next > specific local port > enter 8080 > next > allow the connection>
  4. Next > tick all (domain, private, public) > specify any name
  5. Now you can access your localhost by any device (laptop, mobile, desktop, etc).
  6. Enter ip address in browser url as 123.23.xx.xx:8080 to access localhost by any device.

This IP will be of that device which has the web server.

What's the difference between event.stopPropagation and event.preventDefault?

Terminology

From quirksmode.org:

Event capturing

When you use event capturing

               | |
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  \ /          |     |
|   -------------------------     |
|        Event CAPTURING          |
-----------------------------------

the event handler of element1 fires first, the event handler of element2 fires last.

Event bubbling

When you use event bubbling

               / \
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  | |          |     |
|   -------------------------     |
|        Event BUBBLING           |
-----------------------------------

the event handler of element2 fires first, the event handler of element1 fires last.

Any event taking place in the W3C event model is first captured until it reaches the target element and then bubbles up again.

                 | |  / \
-----------------| |--| |-----------------
| element1       | |  | |                |
|   -------------| |--| |-----------     |
|   |element2    \ /  | |          |     |
|   --------------------------------     |
|        W3C event model                 |
------------------------------------------

Interface

From w3.org, for event capture:

If the capturing EventListener wishes to prevent further processing of the event from occurring it may call the stopPropagation method of the Event interface. This will prevent further dispatch of the event, although additional EventListeners registered at the same hierarchy level will still receive the event. Once an event's stopPropagation method has been called, further calls to that method have no additional effect. If no additional capturers exist and stopPropagation has not been called, the event triggers the appropriate EventListeners on the target itself.

For event bubbling:

Any event handler may choose to prevent further event propagation by calling the stopPropagation method of the Event interface. If any EventListener calls this method, all additional EventListeners on the current EventTarget will be triggered but bubbling will cease at that level. Only one call to stopPropagation is required to prevent further bubbling.

For event cancelation:

Cancelation is accomplished by calling the Event's preventDefault method. If one or more EventListeners call preventDefault during any phase of event flow the default action will be canceled.

Examples

In the following examples, a click on the hyperlink in the web browser triggers the event's flow (the event listeners are executed) and the event target's default action (a new tab is opened).

HTML:

<div id="a">
  <a id="b" href="http://www.google.com/" target="_blank">Google</a>
</div>
<p id="c"></p>

JavaScript:

var el = document.getElementById("c");

function capturingOnClick1(ev) {
    el.innerHTML += "DIV event capture<br>";
}

function capturingOnClick2(ev) {
    el.innerHTML += "A event capture<br>";
}

function bubblingOnClick1(ev) {
    el.innerHTML += "DIV event bubbling<br>";
}

function bubblingOnClick2(ev) {
    el.innerHTML += "A event bubbling<br>";
}

// The 3rd parameter useCapture makes the event listener capturing (false by default)
document.getElementById("a").addEventListener("click", capturingOnClick1, true);
document.getElementById("b").addEventListener("click", capturingOnClick2, true);
document.getElementById("a").addEventListener("click", bubblingOnClick1, false);
document.getElementById("b").addEventListener("click", bubblingOnClick2, false);

Example 1: it results in the output

DIV event capture
A event capture
A event bubbling
DIV event bubbling

Example 2: adding stopPropagation() to the function

function capturingOnClick1(ev) {
    el.innerHTML += "DIV event capture<br>";
    ev.stopPropagation();
}

results in the output

DIV event capture

The event listener prevented further downward and upward propagation of the event. However it did not prevent the default action (a new tab opening).

Example 3: adding stopPropagation() to the function

function capturingOnClick2(ev) {
    el.innerHTML += "A event capture<br>";
    ev.stopPropagation();
}

or the function

function bubblingOnClick2(ev) {
    el.innerHTML += "A event bubbling<br>";
    ev.stopPropagation();
}

results in the output

DIV event capture
A event capture
A event bubbling

This is because both event listeners are registered on the same event target. The event listeners prevented further upward propagation of the event. However they did not prevent the default action (a new tab opening).

Example 4: adding preventDefault() to any function, for instance

function capturingOnClick1(ev) {
    el.innerHTML += "DIV event capture<br>";
    ev.preventDefault();
}

prevents a new tab from opening.

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

This helped me to handle Thread was being aborted exception,

try
{
   //Write HTTP output
    HttpContext.Current.Response.Write(Data);
}  
catch (Exception exc) {}
finally {
   try 
    {
      //stop processing the script and return the current result
      HttpContext.Current.Response.End();
     } 
   catch (Exception ex) {} 
   finally {
        //Sends the response buffer
        HttpContext.Current.Response.Flush();
        // Prevents any other content from being sent to the browser
        HttpContext.Current.Response.SuppressContent = true;
        //Directs the thread to finish, bypassing additional processing
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        //Suspends the current thread
        Thread.Sleep(1);
     }
   }

if you use the following the following code instead of HttpContext.Current.Response.End() , you will get Server cannot append header after HTTP headers have been sent exception.

            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.SuppressContent = True;
            HttpContext.Current.ApplicationInstance.CompleteRequest();

Hope it helps

How to check if div element is empty

You can use the is function

if( $('#cartContent').is(':empty') ) { }

or use the length

if( $('#cartContent:empty').length ) { }

Flutter - Wrap text on overflow, like insert ellipsis or fade

    SizedBox(
                        width: width-100,
                        child: Text(
                          "YOUR LONG TEXT HERE...",
                          maxLines: 3,
                          overflow: TextOverflow.clip,
                          softWrap: true,
                          style: TextStyle(
                            fontWeight:FontWeight.bold,
                          ),
                        ),
                      ),

"Could not find a part of the path" error message

There's something wrong. You have written:

string source_dir = @"E:\\Debug\\VipBat\\{0}";

and the error was

Could not find a part of the path E\Debug\VCCSBat

This is not the same directory.

In your code there's a problem, you have to use:

string source_dir = @"E:\Debug\VipBat"; // remove {0} and the \\ if using @

or

string source_dir = "E:\\Debug\\VipBat"; // remove {0} and the @ if using \\

How to find first element of array matching a boolean condition in JavaScript?

Use findIndex as other previously written. Here's the full example:

function find(arr, predicate) {
    foundIndex = arr.findIndex(predicate);
    return foundIndex !== -1 ? arr[foundIndex] : null;
}

And usage is following (we want to find first element in array which has property id === 1).

var firstElement = find(arr, e => e.id === 1);

Script for rebuilding and reindexing the fragmented index?

To rebuild use:

ALTER INDEX __NAME_OF_INDEX__ ON __NAME_OF_TABLE__ REBUILD

or to reorganize use:

ALTER INDEX __NAME_OF_INDEX__ ON __NAME_OF_TABLE__ REORGANIZE

Reorganizing should be used at lower (<30%) fragmentations but only rebuilding (which is heavier to the database) cuts the fragmentation down to 0%.
For further information see https://msdn.microsoft.com/en-us/library/ms189858.aspx

How to insert a new line in Linux shell script?

The simplest way to insert a new line between echo statements is to insert an echo without arguments, for example:

echo Create the snapshots
echo
echo Snapshot created

That is, echo without any arguments will print a blank line.

Another alternative to use a single echo statement with the -e flag and embedded newline characters \n:

echo -e "Create the snapshots\n\nSnapshot created"

However, this is not portable, as the -e flag doesn't work consistently in all systems. A better way if you really want to do this is using printf:

printf "Create the snapshots\n\nSnapshot created\n"

This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n at the end, as printf doesn't append a newline automatically as echo does.

How do I get rid of the b-prefix in a string in python?

you need to decode the bytes of you want a string:

b = b'1234'
print(b.decode('utf-8'))  # '1234'

Add inline style using Javascript

If you don't want to add each css property line by line, you can do something like this:

_x000D_
_x000D_
document.body.insertAdjacentHTML('afterbegin','<div id="div"></div>');_x000D_
_x000D_
/**_x000D_
 * Add styles to DOM element_x000D_
 * @element DOM element_x000D_
 * @styles object with css styles_x000D_
 */_x000D_
function addStyles(element,styles){_x000D_
  for(id in styles){_x000D_
    element.style[id] = styles[id];_x000D_
  }_x000D_
}_x000D_
_x000D_
// usage_x000D_
var nFilter = document.getElementById('div');_x000D_
var styles = {_x000D_
  color: "red"_x000D_
  ,width: "100px"_x000D_
  ,height: "100px"_x000D_
  ,display: "block"_x000D_
  ,border: "1px solid blue"_x000D_
}_x000D_
addStyles(nFilter,styles);
_x000D_
_x000D_
_x000D_

How to delete a whole folder and content?

Your approach is decent for a folder that only contains files, but if you are looking for a scenario that also contains subfolders then recursion is needed

Also you should capture the return value of the return to make sure you are allowed to delete the file

and include

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

in your manifest

void DeleteRecursive(File dir)
{
    Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
    if (dir.isDirectory())
    {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++)
        {
            File temp = new File(dir, children[i]);
            if (temp.isDirectory())
            {
                Log.d("DeleteRecursive", "Recursive Call" + temp.getPath());
                DeleteRecursive(temp);
            }
            else
            {
                Log.d("DeleteRecursive", "Delete File" + temp.getPath());
                boolean b = temp.delete();
                if (b == false)
                {
                    Log.d("DeleteRecursive", "DELETE FAIL");
                }
            }
        }

    }
    dir.delete();
}

How to have image and text side by side

Your h4 has some crazy margin on it, so remove it

h4 {
    margin:0px;
}

http://jsfiddle.net/qMdfC/2/

edit:

http://jsfiddle.net/qMdfC/6/

for the 0 minutes text, added a float left to the first div, but personally i'd just combine them, although you may have reasons not to.

Detect rotation of Android phone in the browser with JavaScript

A little contribution to the two-bit-fool's answer:

As described on the table on droid phones "orientationchange" event gets fired earlier than "resize" event thus blocking the next resize call (because of the if statement). Width property is still not set.

A workaround though maybe not a perfect one could be to not fire the "orientationchange" event. That can be archived by wrapping "orientationchange" event binding in "if" statement:

if (!navigator.userAgent.match(/android/i))
{
    window.addEventListener("orientationchange", checkOrientation, false);
}

Hope it helps

(tests were done on Nexus S)

creating an array of structs in c++

It works perfectly. I have gcc compiler C++11 ready. Try this and you'll see:

#include <iostream>

using namespace std;

int main()
{
    int pause;

    struct Customer
    {
           int uid;
           string name;
    };

    Customer customerRecords[2];
    customerRecords[0] = {25, "Bob Jones"};
    customerRecords[1] = {26, "Jim Smith"};
    cout << customerRecords[0].uid << " " << customerRecords[0].name << endl;
    cout << customerRecords[1].uid << " " << customerRecords[1].name << endl;
    cin >> pause;
return 0;
}

How do I make an asynchronous GET request in PHP?

This works fine for me, sadly you cannot retrieve the response from your request:

<?php
header("http://mahwebsite.net/myapp.php?var=dsafs");
?>

It works very fast, no need for raw tcp sockets :)

How to make a list of n numbers in Python and randomly select any number?

You can use:

import random
random.choice(range(n))

or:

random.choice(range(1,n+1))

if you want it from 1 to n and not from 0.

Checking if type == list in python

Your issue is that you have re-defined list as a variable previously in your code. This means that when you do type(tmpDict[key])==list if will return False because they aren't equal.

That being said, you should instead use isinstance(tmpDict[key], list) when testing the type of something, this won't avoid the problem of overwriting list but is a more Pythonic way of checking the type.

Swift Beta performance: sorting arrays

From The Swift Programming Language:

The Sort Function Swift’s standard library provides a function called sort, which sorts an array of values of a known type, based on the output of a sorting closure that you provide. Once it completes the sorting process, the sort function returns a new array of the same type and size as the old one, with its elements in the correct sorted order.

The sort function has two declarations.

The default declaration which allows you to specify a comparison closure:

func sort<T>(array: T[], pred: (T, T) -> Bool) -> T[]

And a second declaration that only take a single parameter (the array) and is "hardcoded to use the less-than comparator."

func sort<T : Comparable>(array: T[]) -> T[]

Example:
sort( _arrayToSort_ ) { $0 > $1 }

I tested a modified version of your code in a playground with the closure added on so I could monitor the function a little more closely, and I found that with n set to 1000, the closure was being called about 11,000 times.

let n = 1000
let x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
    x[i] = random()
}
let y = sort(x) { $0 > $1 }

It is not an efficient function, an I would recommend using a better sorting function implementation.

EDIT:

I took a look at the Quicksort wikipedia page and wrote a Swift implementation for it. Here is the full program I used (in a playground)

import Foundation

func quickSort(inout array: Int[], begin: Int, end: Int) {
    if (begin < end) {
        let p = partition(&array, begin, end)
        quickSort(&array, begin, p - 1)
        quickSort(&array, p + 1, end)
    }
}

func partition(inout array: Int[], left: Int, right: Int) -> Int {
    let numElements = right - left + 1
    let pivotIndex = left + numElements / 2
    let pivotValue = array[pivotIndex]
    swap(&array[pivotIndex], &array[right])
    var storeIndex = left
    for i in left..right {
        let a = 1 // <- Used to see how many comparisons are made
        if array[i] <= pivotValue {
            swap(&array[i], &array[storeIndex])
            storeIndex++
        }
    }
    swap(&array[storeIndex], &array[right]) // Move pivot to its final place
    return storeIndex
}

let n = 1000
var x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
    x[i] = Int(arc4random())
}

quickSort(&x, 0, x.count - 1) // <- Does the sorting

for i in 0..n {
    x[i] // <- Used by the playground to display the results
}

Using this with n=1000, I found that

  1. quickSort() got called about 650 times,
  2. about 6000 swaps were made,
  3. and there are about 10,000 comparisons

It seems that the built-in sort method is (or is close to) quick sort, and is really slow...

Command-line Git on Windows

As @birryree said, add msysgit's binary to your PATH, or use Git Bash (installed with msysgit as far as I remember) which is better than Windows' console and similar to the Unix one.

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

DLL References in Visual C++

You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?

Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.

Alter a SQL server function to accept new optional parameter

The way to keep SELECT dbo.fCalculateEstimateDate(647) call working is:

ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100)  AS
   Declare @Result varchar(100)
   SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
   Return @Result
Begin
End

CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100)  AS
Begin
  <Function Body>
End

java.lang.ClassCastException

@Lauren?iu Dascalu's answer explains how / why you get a ClassCastException.

Your exception message looks rather suspicious to me, but it might help you to know that "[Lcom.rsa.authagent.authapi.realmstat.AUTHw" means that the actual type of the object that you were trying to cast was com.rsa.authagent.authapi.realmstat.AUTHw[]; i.e. it was an array object.

Normally, the next steps to solving a problem like this are:

  • examining the stacktrace to figure out which line of which class threw the exception,
  • examining the corresponding source code, to see what the expected type, and
  • tracing back to see where the object with the "wrong" type came from.

Is there a CSS selector for the first direct child only?

What you posted literally means "Find any divs that are inside of section divs and are the first child of their parent." The sub contains one tag that matches that description.

It is unclear to me whether you want both children of the main div or not. If so, use this:

div.section > div

If you only want the header, use this:

div.section > div:first-child

Using the > changes the description to: "Find any divs that are the direct descendents of section divs" which is what you want.

Please note that all major browsers support this method, except IE6. If IE6 support is mission-critical, you will have to add classes to the child divs and use that, instead. Otherwise, it's not worth caring about.

How to create JSON object using jQuery

var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({    url: 'test/set',
                        type: "POST",
                        data: model,
                        success: function (res) {
                            if (res != null) {
                                alert("done.");
                            }
                        },
                        error: function (res) {

                        }
                    });

UITextField text change event

You should use the notification to solve this problem,because the other method will listen to the input box not the actually input,especially when you use the Chinese input method. In viewDidload

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:)
                                                 name:@"UITextFieldTextDidChangeNotification"
                                               object:youTarget];

then

- (void)textFiledEditChanged:(NSNotification *)obj {
UITextField *textField = (UITextField *)obj.object;
NSString *toBestring = textField.text;
NSArray *currentar = [UITextInputMode activeInputModes];
UITextInputMode *currentMode = [currentar firstObject];
if ([currentMode.primaryLanguage isEqualToString:@"zh-Hans"]) {
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    if (!position) {
        if (toBestring.length > kMaxLength)
            textField.text =  toBestring;
} 

}

finally,you run,will done.

How to change Android version and code version number?

You can easily auto increase versionName and versionCode programmatically.

For Android add this to your gradle script and also create a file version.properties with VERSION_CODE=555

android {
        compileSdkVersion 30
        buildToolsVersion "30.0.3"
    
        def versionPropsFile = file('version.properties')
        if (versionPropsFile.canRead()) {
            def Properties versionProps = new Properties()
    
            versionProps.load(new FileInputStream(versionPropsFile))
    
            def code = versionProps['VERSION_CODE'].toInteger() + 1
    
            versionProps['VERSION_CODE'] = code.toString()
            versionProps.store(versionPropsFile.newWriter(), null)
    
    
            defaultConfig {
                applicationId "app.umanusorn.playground"
                minSdkVersion 29
                targetSdkVersion 30
                versionCode code
                versionName code.toString()

Inserting a tab character into text using C#

When using literal strings (start with @") this might be easier

char tab = '\u0009';
string A = "Apple";
string B = "Bob";
string myStr = String.Format(@"{0}:{1}{2}", A, tab, B);

Would result in Apple:<tab>Bob

Jenkins - How to access BUILD_NUMBER environment variable

Assuming I am understanding your question and setup correctly,

If you're trying to use the build number in your script, you have two options:

1) When calling ant, use: ant -Dbuild_parameter=${BUILD_NUMBER}

2) Change your script so that:

<property environment="env" />
<property name="build_parameter"  value="${env.BUILD_NUMBER}"/>

jQuery - Call ajax every 10 seconds

You could try setInterval() instead:

var i = setInterval(function(){
   //Call ajax here
},10000)

SQL Server: use CASE with LIKE

SELECT Lname, Cods, CASE WHEN Lname LIKE '% HN%' THEN SUBSTRING(Lname, 
CHARINDEX(' ', Lname) - 50, 50) WHEN Lname LIKE 'HN%' THEN Lname ELSE 
Lname END AS LnameTrue FROM dbo.____Fname_Lname

Alternative to iFrames with HTML5

No, there isn't an equivalent. The <iframe> element is still valid in HTML5. Depending on what exact interaction you need there might be different APIs. For example there's the postMessage method which allows you to achieve cross domain javascript interaction. But if you want to display cross domain HTML contents (styled with CSS and made interactive with javascript) iframe stays as a good way to do.

Download File Using jQuery

Here's a nice article that shows many ways of hiding files from search engines:

http://antezeta.com/news/avoid-search-engine-indexing

JavaScript isn't a good way not to index a page; it won't prevent users from linking directly to your files (and thus revealing it to crawlers), and as Rob mentioned, wouldn't work for all users.
An easy fix is to add the rel="nofollow" attribute, though again, it's not complete without robots.txt.

<a href="uploads/file.doc" rel="nofollow">Download Here</a>

getting the X/Y coordinates of a mouse click on an image with jQuery

The below code works always even if any image makes the window scroll.

$(function() {
    $("#demo-box").click(function(e) {

      var offset = $(this).offset();
      var relativeX = (e.pageX - offset.left);
      var relativeY = (e.pageY - offset.top);

      alert("X: " + relativeX + "  Y: " + relativeY);

    });
});

Ref: http://css-tricks.com/snippets/jquery/get-x-y-mouse-coordinates/

How to correct indentation in IntelliJ

Ctrl + Alt + L works with Android Studio under xfce4 on Linux. I see that Gnome used to use this shortcut for lock screen, but in Gnome 3 it was changed to Super+L (AKA Windows+L): https://wiki.gnome.org/Design/OS/KeyboardShortcuts

How to add empty spaces into MD markdown readme on GitHub?

You can use <pre> to display all spaces & blanks you have typed. E.g.:

<pre>
hello, this is
   just an     example
....
</pre>

Get path of executable

QT provides this with OS abstraction as QCoreApplication::applicationDirPath()

Extract MSI from EXE

For InstallShield MSI based projects I have found the following to work:

setup.exe /s /x /b"C:\FolderInWhichMSIWillBeExtracted" /v"/qn"

This command will lead to an extracted MSI in a directory you can freely specify and a silently failed uninstall of the product.

The command line basically tells the setup.exe to attempt to uninstall the product (/x) and do so silently (/s). While doing that it should extract the MSI to a specific location (/b).

The /v command passes arguments to Windows Installer, in this case the /qn argument. The /qn argument disables any GUI output of the installer.

What does the servlet <load-on-startup> value signify

Resin 3.0 documents this behavior:

load-on-startup can specify an (optional) integer value. If the value is 0 or greater, it indicates an order for servlets to be loaded, servlets with higher numbers get loaded after servlets with lower numbers.

The JSP 3.1 spec (JSR 340) says this on page 14-160:

The element load-on-startup indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the Web application. The element content of this element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-startup value.

You probably want to check not only the JSR, but also the documentation for your web container. There may be differences

How can I center a div within another div?

Technically, your inner DIV (#container) is centered horizontally. The reason you can't tell is because with the CSS width: auto property the inner DIV is expanding to the same width as its parent.

See this fiddle: http://jsfiddle.net/UZ4AE/

#container {
    width: 50px;
    height: auto;
    margin: 0 auto;
    padding: 10px;
    position: relative;
    background-color: red;
}

In this example, I simply set the width of #container to 50px and set the background to red so that you can see that it is centered.

I think the real question is "How do I center elements horizontally with CSS?" and the answer is (drum roll please): it depends!

I won't do a full rehash of the myriad ways to center things with CSS when W3Schools does it so nicely here: http://www.w3schools.com/css/css_align.asp but the basic idea is that for block level elements you simply specify the desired width and set the left and right margins to auto.

.center {
    margin-left: auto;
    margin-right: auto;
    width: 50px;
}

Please note: This answer only applies to block level elements! To position an inline element, you will need to use the text-align: center property on the first block parent.

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

Use

sudo pip install virtualenv

Apparently you will have powers of administrator when adding "sudo" before the line... just don't forget your password.

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

Store the previous checked radio in a variable:
http://jsfiddle.net/dsbonev/C5S4B/

HTML

<input type="radio" name="myRadios" value="1" /> 1
<input type="radio" name="myRadios" value="2" /> 2
<input type="radio" name="myRadios" value="3" /> 3
<input type="radio" name="myRadios" value="4" /> 4
<input type="radio" name="myRadios" value="5" /> 5

JS

var changeHandler = (function initChangeHandler() {
    var previousCheckedRadio = null;

    var result = function (event) {
        var currentCheckedRadio = event.target;
        var name = currentCheckedRadio.name;

        if (name !== 'myRadios') return;

        //using radio elements previousCheckedRadio and currentCheckedRadio

        //storing radio element for using in future 'change' event handler
        previousCheckedRadio = currentCheckedRadio;
    };

    return result;
})();

document.addEventListener('change', changeHandler, false);

JS EXAMPLE CODE

var changeHandler = (function initChangeHandler() {
    var previousCheckedRadio = null;

    function logInfo(info) {
        if (!console || !console.log) return;

        console.log(info);
    }

    function logPrevious(element) {
        if (!element) return;

        var message = element.value + ' was unchecked';

        logInfo(message);
    }

    function logCurrent(element) {
        if (!element) return;

        var message = element.value + ' is checked';

        logInfo(message);
    }

    var result = function (event) {
        var currentCheckedRadio = event.target;
        var name = currentCheckedRadio.name;

        if (name !== 'myRadios') return;

        logPrevious(previousCheckedRadio);
        logCurrent(currentCheckedRadio);

        previousCheckedRadio = currentCheckedRadio;
    };

    return result;
})();

document.addEventListener('change', changeHandler, false);

Using PowerShell to remove lines from a text file if it contains a string

Escape the | character using a backtick

get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

How to avoid page refresh after button click event in asp.net

Page got refreshed when a trip to server is made, and server controls like Button has a property AutoPostback = true by default which means whenever they are clicked a trip to server will be made. Set AutoPostback = false for insert button, and this will do the trick for you.

How do I concatenate a string with a variable?

Another way to do it simpler using jquery.

sample:

function add(product_id){

    // the code to add the product
    //updating the div, here I just change the text inside the div. 
    //You can do anything with jquery, like change style, border etc.
    $("#added_"+product_id).html('the product was added to list');

}

Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.

Best Regards!

Installing Node.js (and npm) on Windows 10

New installers (.msi downloaded from https://nodejs.org) have "Add to PATH" option. By default it is selected. Make sure that you leave it checked.

Add to PATH

Get the first element of an array

There are too many answers here, and the selected answer will work for most of the cases.

In my case, I had a 2D array, and array_values for some odd reason was removing the keys on the inner arrays. So I end up with this:

$keys = array_keys($myArray); // Fetches all the keys
$firstElement = $myArray[$keys[0]]; // Get the first element using first key

How to handle-escape both single and double quotes in an SQL-Update statement

Use two single quotes to escape them in the sql statement. The double quotes should not be a problem:

SELECT 'How is my son''s school helping him learn?  "Not as good as Stack Overflow would!"'

Print:

How is my son's school helping him learn? "Not as good as Stack Overflow would!"

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

How to start MySQL server on windows xp

probably this will help you I was also having problem with starting MySql server but run command as mention right mark in picture . Its working fine .

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/vnd.microsoft.icon, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon.

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

Bulk Record Update with SQL

Your way is correct, and here is another way you can do it:

update      Table1
set         Description = t2.Description
from        Table1 t1
inner join  Table2 t2
on          t1.DescriptionID = t2.ID

The nested select is the long way of just doing a join.

Execution failed for task ':app:processDebugResources' even with latest build tools

this issue comes up with 2 reasons

1) the android SDK has not been install 2) the build toold version corresponsind to the android SDK is not installed

to start open terminal and type android and install API 26(updated one) and build tools version 26.0.1 or 26.0.2 then try to run using command ionic cordova build android

Accessing members of items in a JSONArray with Java

Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray with java8 Stream API.

import org.json.JSONArray;
import org.json.JSONObject;

@Test
public void access_org_JsonArray() {
    //Given: array
    JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
                    new HashMap() {{
                        put("a", 100);
                        put("b", 200);
                    }}
            ),
            new JSONObject(
                    new HashMap() {{
                        put("a", 300);
                        put("b", 400);
                    }}
            )));

    //Then: convert to List<JSONObject>
    List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .collect(Collectors.toList());

    // you can access the array elements now
    jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
    // prints 100, 300
}

If the iteration is only one time, (no need to .collect)

    IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .forEach(item -> {
               System.out.println(item);
            });

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

I ran into the 'Expecting: ANY PRIVATE KEY' error when using openssl on Windows (Ubuntu Bash and Git Bash had the same issue).

The cause of the problem was that I'd saved the key and certificate files in Notepad using UTF8. Resaving both files in ANSI format solved the problem.

Where is the php.ini file on a Linux/CentOS PC?

#php -i | grep php.ini also will work too!

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Set the path of the root folder and after run the below command

ex : cd C:\Users\maha\Documents\gradle\gs-gradle-master\initial

How to insert a large block of HTML in JavaScript?

The easiest way to insert html blocks is to use template strings (backticks). It will also allow you to insert dynamic content via ${...}:

document.getElementById("log-menu").innerHTML = `
            <a href="#"> 
               ${data.user.email}
            </a>
            <div class="dropdown-menu p-3 dropdown-menu-right">
                <div class="form-group">
                    <label for="email1">Logged in as:</label>
                    <p>${data.user.email}</p>
                </div>
                <button onClick="getLogout()" ">Sign out</button>
            </div>
    `

Sample database for exercise

You want huge?

Here's a small table: create table foo (id int not null primary key auto_increment, crap char(2000));

insert into foo(crap) values ('');

-- each time you run the next line, the number of rows in foo doubles. insert into foo( crap ) select * from foo;

run it twenty more times, you have over a million rows to play with.

Yes, if he's looking for looks of relations to navigate, this is not the answer. But if by huge he means to test performance and his ability to optimize, this will do it. I did exactly this (and then updated with random values) to test an potential answer I had for another question. (And didn't answer it, because I couldn't come up with better performance than what that asker had.)

Had he asked for "complex", I'd have gien a differnt answer. To me,"huge" implies "lots of rows".

Because you don't need huge to play with tables and relations. Consider a table, by itself, with no nullable columns. How many different kinds of rows can there be? Only one, as all columns must have some value as none can be null.

Every nullable column multiples by two the number of different kinds of rows possible: a row where that column is null, an row where it isn't null.

Now consider the table, not in isolation. Consider a table that is a child table: for every child that has an FK to the parent, that, is a many-to-one, there can be 0, 1 or many children. So we multiply by three times the count we got in the previous step (no rows for zero, one for exactly one, two rows for many). For any grandparent to which the parent is a many, another three.

For many-to-many relations, we can have have no relation, a one-to-one, a one-to-many, many-to-one, or a many-to-many. So for each many-to-many we can reach in a graph from the table, we multiply the rows by nine -- or just like two one-to manys. If the many-to-many also has data, we multiply by the nullability number.

Tables that we can't reach in our graph -- those that we have no direct or indirect FK to, don't multiply the rows in our table.

By recursively multiplying the each table we can reach, we can come up with the number of rows needed to provide one of each "kind", and we need no more than those to test every possible relation in our schema. And we're nowhere near huge.

@Autowired and static method

Use AppContext. Make sure you create a bean in your context file.

private final static Foo foo = AppContext.getApplicationContext().getBean(Foo.class);

public static void randomMethod() {
     foo.doStuff();
}

Getting the first index of an object

ES6

const [first] = Object.keys(obj)

Where is database .bak file saved from SQL Server Management Studio?

I dont think default backup location is stored within the SQL server itself. The settings are stored in Registry. Look for "BackupDirectory" key and you'll find the default backup.

The "msdb.dbo.backupset" table consists of list of backups taken, if no backup is taken for a database, it won't show you anything

Displaying output of a remote command with Ansible

Prints pubkey and avoid the changed status by adding changed_when: False to cat task:

- name: Generate SSH keys for vagrant user   
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048

- name: Check SSH public key   
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
  changed_when: False

- name: Print SSH public key
  debug: var=cat.stdout

- name: Wait for user to copy SSH public key   
  pause: prompt="Please add the SSH public key above to your GitHub account"

How do I clone a generic list in C#?

If your elements are value types, then you can just do:

List<YourType> newList = new List<YourType>(oldList);

However, if they are reference types and you want a deep copy (assuming your elements properly implement ICloneable), you could do something like this:

List<ICloneable> oldList = new List<ICloneable>();
List<ICloneable> newList = new List<ICloneable>(oldList.Count);

oldList.ForEach((item) =>
    {
        newList.Add((ICloneable)item.Clone());
    });

Obviously, replace ICloneable in the above generics and cast with whatever your element type is that implements ICloneable.

If your element type doesn't support ICloneable but does have a copy-constructor, you could do this instead:

List<YourType> oldList = new List<YourType>();
List<YourType> newList = new List<YourType>(oldList.Count);

oldList.ForEach((item)=>
    {
        newList.Add(new YourType(item));
    });

Personally, I would avoid ICloneable because of the need to guarantee a deep copy of all members. Instead, I'd suggest the copy-constructor or a factory method like YourType.CopyFrom(YourType itemToCopy) that returns a new instance of YourType.

Any of these options could be wrapped by a method (extension or otherwise).

How can I switch views programmatically in a view controller? (Xcode, iPhone)

If you're in a Navigation Controller:

ViewController *viewController = [[ViewController alloc] init];
[self.navigationController pushViewController:viewController animated:YES];

or if you just want to present a new view:

ViewController *viewController = [[ViewController alloc] init];    
[self presentViewController:viewController animated:YES completion:nil];

How do I use floating-point division in bash?

As others have indicated, bash does not have built-in floating-point operators.

You can implement floating-point in bash, even without using calculator programs like bc and awk, or any external programs for that matter.

I'm doing exactly this in my project, shellmath, in three basic steps:

  1. Break the numbers down into their integer and fractional parts
  2. Use the built-in integer operators to process the parts separately while being careful about place-value and carrying
  3. Recombine the results

As a teaser, I've added a demo script that calculates e using its Taylor series centered at x=0.

Please check it out if you have a moment. I welcome your feedback!

What is the most efficient way to get first and last line of a text file?

To read both the first and final line of a file you could...

  • open the file, ...
  • ... read the first line using built-in readline(), ...
  • ... seek (move the cursor) to the end of the file, ...
  • ... step backwards until you encounter EOL (line break) and ...
  • ... read the last line from there.
def readlastline(f):
    f.seek(-2, 2)              # Jump to the second last byte.
    while f.read(1) != b"\n":  # Until EOL is found ...
        f.seek(-2, 1)          # ... jump back, over the read byte plus one more.
    return f.read()            # Read all data from this point on.
    
with open(file, "rb") as f:
    first = f.readline()
    last = readlastline(f)

Jump to the second last byte directly to prevent trailing newline characters to cause empty lines to be returned*.

The current offset is pushed ahead by one every time a byte is read so the stepping backwards is done two bytes at a time, past the recently read byte and the byte to read next.

The whence parameter passed to fseek(offset, whence=0) indicates that fseek should seek to a position offset bytes relative to...

* As would be expected as the default behavior of most applications, including print and echo, is to append one to every line written and has no effect on lines missing trailing newline character.


Efficiency

1-2 million lines each and I have to do this for several hundred files.

I timed this method and compared it against against the top answer.

10k iterations processing a file of 6k lines totalling 200kB: 1.62s vs 6.92s.
100 iterations processing a file of 6k lines totalling 1.3GB: 8.93s vs 86.95.

Millions of lines would increase the difference a lot more.

Exakt code used for timing:

with open(file, "rb") as f:
    first = f.readline()     # Read and store the first line.
    for last in f: pass      # Read all lines, keep final value.

Amendment

A more complex, and harder to read, variation to address comments and issues raised since.

  • Return empty string when parsing empty file, raised by comment.
  • Return all content when no delimiter is found, raised by comment.
  • Avoid relative offsets to support text mode, raised by comment.
  • UTF16/UTF32 hack, noted by comment.

Also adds support for multibyte delimiters, readlast(b'X<br>Y', b'<br>', fixed=False).

Please note that this variation is really slow for large files because of the non-relative offsets needed in text mode. Modify to your need, or do not use it at all as you're probably better off using f.readlines()[-1] with files opened in text mode.

#!/bin/python3

from os import SEEK_END

def readlast(f, sep, fixed=True):
    r"""Read the last segment from a file-like object.

    :param f: File to read last line from.
    :type  f: file-like object
    :param sep: Segment separator (delimiter).
    :type  sep: bytes, str
    :param fixed: Treat data in ``f`` as a chain of fixed size blocks.
    :type  fixed: bool
    :returns: Last line of file.
    :rtype: bytes, str
    """
    bs   = len(sep)
    step = bs if fixed else 1
    if not bs:
        raise ValueError("Zero-length separator.")
    try:
        o = f.seek(0, SEEK_END)
        o = f.seek(o-bs-step)    # - Ignore trailing delimiter 'sep'.
        while f.read(bs) != sep: # - Until reaching 'sep': Read sep-sized block
            o = f.seek(o-step)   #  and then seek to the block to read next.
    except (OSError,ValueError): # - Beginning of file reached.
        f.seek(0)
    return f.read()

def test_readlast():
    from io import BytesIO, StringIO
    
    # Text mode.
    f = StringIO("first\nlast\n")
    assert readlast(f, "\n") == "last\n"
    
    # Bytes.
    f = BytesIO(b'first|last')
    assert readlast(f, b'|') == b'last'
    
    # Bytes, UTF-8.
    f = BytesIO("X\nY\n".encode("utf-8"))
    assert readlast(f, b'\n').decode() == "Y\n"
    
    # Bytes, UTF-16.
    f = BytesIO("X\nY\n".encode("utf-16"))
    assert readlast(f, b'\n\x00').decode('utf-16') == "Y\n"
  
    # Bytes, UTF-32.
    f = BytesIO("X\nY\n".encode("utf-32"))
    assert readlast(f, b'\n\x00\x00\x00').decode('utf-32') == "Y\n"
    
    # Multichar delimiter.
    f = StringIO("X<br>Y")
    assert readlast(f, "<br>", fixed=False) == "Y"
    
    # Make sure you use the correct delimiters.
    seps = { 'utf8': b'\n', 'utf16': b'\n\x00', 'utf32': b'\n\x00\x00\x00' }
    assert "\n".encode('utf8' )     == seps['utf8']
    assert "\n".encode('utf16')[2:] == seps['utf16']
    assert "\n".encode('utf32')[4:] == seps['utf32']
    
    # Edge cases.
    edges = (
        # Text , Match
        (""    , ""  ), # Empty file, empty string.
        ("X"   , "X" ), # No delimiter, full content.
        ("\n"  , "\n"),
        ("\n\n", "\n"),
        # UTF16/32 encoded U+270A (b"\n\x00\n'\n\x00"/utf16)
        (b'\n\xe2\x9c\x8a\n'.decode(), b'\xe2\x9c\x8a\n'.decode()),
    )
    for txt, match in edges:
        for enc,sep in seps.items():
            assert readlast(BytesIO(txt.encode(enc)), sep).decode(enc) == match

if __name__ == "__main__":
    import sys
    for path in sys.argv[1:]:
        with open(path) as f:
            print(f.readline()    , end="")
            print(readlast(f,"\n"), end="")

What are the differences between .gitignore and .gitkeep?

Many people prefer to use just .keep since the convention has nothing to do with git.

Count number of tables in Oracle

Yeah sure your query will work just modify it a little. Look here for refrence : http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2105.htm#i1592091

Run this:

SELECT TABLE_NAME FROM DBA_TABLES;

to get list of tables.

and Run this:

SELECT Count(*) FROM DBA_TABLES;

to get the count of tables.

Better way to generate array of all letters in the alphabet

Check this once I'm sure you will get a to z alphabets:

for (char c = 'a'; c <= 'z'; c++) {
    al.add(c);
}
System.out.println(al);'

How do I use Safe Area Layout programmatically?

Swift 4.2 and 5.0. Suppose you wan to add Leading, Trailing, Top and Bottom constraints on viewBg. So, you can use the below code.

let guide = self.view.safeAreaLayoutGuide
viewBg.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
viewBg.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
viewBg.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
viewBg.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true

UILabel with text of two different colors

extension UILabel{

    func setSubTextColor(pSubString : String, pColor : UIColor){


        let attributedString: NSMutableAttributedString = self.attributedText != nil ? NSMutableAttributedString(attributedString: self.attributedText!) : NSMutableAttributedString(string: self.text!);


        let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive)
        if range.location != NSNotFound {
            attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range);
        }
        self.attributedText = attributedString

    }
}

Clicking URLs opens default browser

Add this 2 lines in your code -

mWebView.setWebChromeClient(new WebChromeClient()); 
mWebView.setWebViewClient(new WebViewClient());?

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

How to check if a subclass is an instance of a class at runtime?

if(view instanceof B)

This will return true if view is an instance of B or the subclass A (or any subclass of B for that matter).

How can I create a product key for my C# application?

I'm going to piggyback a bit on @frankodwyer's great answer and dig a little deeper into online-based licensing. I'm the founder of Keygen, a licensing REST API built for developers.

Since you mentioned wanting 2 "types" of licenses for your application, i.e. a "full version" and a "trial version", we can simplify that and use a feature license model where you license specific features of your application (in this case, there's a "full" feature-set and a "trial" feature-set).

To start off, we could create 2 license types (called policies in Keygen) and whenever a user registers an account you can generate a "trial" license for them to start out (the "trial" license implements our "trial" feature policy), which you can use to do various checks within the app e.g. can user use Trial-Feature-A and Trial-Feature-B.

And building on that, whenever a user purchases your app (whether you're using PayPal, Stripe, etc.), you can generate a license implementing the "full" feature policy and associate it with the user's account. Now within your app you can check if the user has a "full" license that can do Pro-Feature-X and Pro-Feature-Y (by doing something like user.HasLicenseFor(FEATURE_POLICY_ID)).

I mentioned allowing your users to create user accounts—what do I mean by that? I've gone into this in detail in a couple other answers, but a quick rundown as to why I think this is a superior way to authenticate and identify your users:

  1. User accounts let you associate multiple licenses and multiple machines to a single user, giving you insight into your customer's behavior and to prompt them for "in-app purchases" i.e. purchasing your "full" version (kind of like mobile apps).
  2. We shouldn't require our customers to input long license keys, which are both tedious to input and hard to keep track of i.e. they get lost easily. (Try searching "lost license key" on Twitter!)
  3. Customers are accustomed to using an email/password; I think we should do what people are used to doing so that we can provide a good user experience (UX).

Of course, if you don't want to handle user accounts and you want your users to input license keys, that's completely fine (and Keygen supports doing that as well). I'm just offering another way to go about handling that aspect of licensing and hopefully provide a nice UX for your customers.

Finally since you also mentioned that you want to update these licenses annually, you can set a duration on your policies so that "full" licenses will expire after a year and "trial" licenses last say 2 weeks, requiring that your users purchase a new license after expiration.

I could dig in more, getting into associating machines with users and things like that, but I thought I'd try to keep this answer short and focus on simply licensing features to your users.

How to convert "0" and "1" to false and true

You can use that form:

return returnValue.Equals("1") ? true : false;

Or more simply (thanks to Jurijs Kastanovs):

return returnValue.Equals("1");

Redirect form to different URL based on select option element

Just use a onchnage Event for select box.

<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
    <option value="https://www.yahoo.com/" selected>Option1</option>
    <option value="https://www.google.co.in/">Option2</option>
    <option value="https://www.gmail.com/">Option3</option>

</select>

And if selected option to be loaded at the page load then add some javascript code

<script type="text/javascript">
    window.onload = function(){
        location.href=document.getElementById("selectbox").value;
    }       
</script>

for jQuery: Remove the onchange event from <select> tag

jQuery(function () {
    // remove the below comment in case you need chnage on document ready
    // location.href=jQuery("#selectbox").val(); 
    jQuery("#selectbox").change(function () {
        location.href = jQuery(this).val();
    })
})

How to dispatch a Redux action with a timeout?

It is simple. Use trim-redux package and write like this in componentDidMount or other place and kill it in componentWillUnmount.

componentDidMount() {
  this.tm = setTimeout(function() {
    setStore({ age: 20 });
  }, 3000);
}

componentWillUnmount() {
  clearTimeout(this.tm);
}

Using margin / padding to space <span> from the rest of the <p>

JSFiddle

HTML:

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa omnis obcaecati dolore reprehenderit praesentium. Nisi eius deleniti voluptates quis esse deserunt magni eum commodi nostrum facere pariatur sed eos voluptatum?

</p><span class="small-text">George Nelson 1955</span>

CSS:

p       {font-size:24px; font-weight: 300; -webkit-font-smoothing: subpixel-antialiased;}
p span  {font-size:16px; font-style: italic; margin-top:50px;}

.small-text{
font-size: 12px;
font-style: italic;
}

How to sort a list of strings?

Old question, but if you want to do locale-aware sorting without setting locale.LC_ALL you can do so by using the PyICU library as suggested by this answer:

import icu # PyICU

def sorted_strings(strings, locale=None):
    if locale is None:
       return sorted(strings)
    collator = icu.Collator.createInstance(icu.Locale(locale))
    return sorted(strings, key=collator.getSortKey)

Then call with e.g.:

new_list = sorted_strings(list_of_strings, "de_DE.utf8")

This worked for me without installing any locales or changing other system settings.

(This was already suggested in a comment above, but I wanted to give it more prominence, because I missed it myself at first.)

How to resolve javax.mail.AuthenticationFailedException issue?

You need to implement a custom Authenticator

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;


class GMailAuthenticator extends Authenticator {
     String user;
     String pw;
     public GMailAuthenticator (String username, String password)
     {
        super();
        this.user = username;
        this.pw = password;
     }
    public PasswordAuthentication getPasswordAuthentication()
    {
       return new PasswordAuthentication(user, pw);
    }
}

Now use it in the Session

Session session = Session.getInstance(props, new GMailAuthenticator(username, password));

Also check out the JavaMail FAQ

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

Just set the selectIndex of the associated <select> tag to -1 as the last step of your processing event.

mySelect = document.getElementById("idlist");
mySelect.selectedIndex = -1; 

It works every time, removing the highlight and allowing you to select the same (or different) element again .

java.math.BigInteger cannot be cast to java.lang.Long

Your error might be in this line:

List<Long> result = query.list();

where query.list() is returning a BigInteger List instead of Long list. Try to change it to.

List<BigInteger> result = query.list();

C# ASP.NET Send Email via TLS

TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL.

Form Validation With Bootstrap (jQuery)

I had your code setup on jsFiddle to try diagnose the problem.

http://jsfiddle.net/5WMff/

However, I don't seem to encounter your issue. Could you take a look and let us know?

HTML

<div class="hero-unit">
 <h1>Contact Form</h1> 
</br>
<form method="POST" action="contact-form-submission.php" class="form-horizontal" id="contact-form">
    <div class="control-group">
        <label class="control-label" for="name">Name</label>
        <div class="controls">
            <input type="text" name="name" id="name" placeholder="Your name">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="email">Email Address</label>
        <div class="controls">
            <input type="text" name="email" id="email" placeholder="Your email address">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="subject">Subject</label>
        <div class="controls">
            <select id="subject" name="subject">
                <option value="na" selected="">Choose One:</option>
                <option value="service">Feedback</option>
                <option value="suggestions">Suggestion</option>
                <option value="support">Question</option>
                <option value="other">Other</option>
            </select>
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="message">Message</label>
        <div class="controls">
            <textarea name="message" id="message" rows="8" class="span5" placeholder="The message you want to send to us."></textarea>
        </div>
    </div>
    <div class="form-actions">
        <input type="hidden" name="save" value="contact">
        <button type="submit" class="btn btn-success">Submit Message</button>
        <button type="reset" class="btn">Cancel</button>
    </div>
</form>

Javascript

$(document).ready(function () {

$('#contact-form').validate({
    rules: {
        name: {
            minlength: 2,
            required: true
        },
        email: {
            required: true,
            email: true
        },
        message: {
            minlength: 2,
            required: true
        }
    },
    highlight: function (element) {
        $(element).closest('.control-group').removeClass('success').addClass('error');
    },
    success: function (element) {
        element.text('OK!').addClass('valid')
            .closest('.control-group').removeClass('error').addClass('success');
    }
});
});

How to grep (search) committed code in the Git history

Adding more to the answers already present. If you know the file in which you might have made do this:

git log --follow -p -S 'search-string' <file-path>

--follow: lists the history of a file

JavaFX: How to get stage from controller during initialization?

The simplest way to get stage object in controller is:

  1. Add an extra method in own created controller class like (it will be a setter method to set the stage in controller class),

    private Stage myStage;
    public void setStage(Stage stage) {
         myStage = stage;
    }
    
  2. Get controller in start method and set stage

    FXMLLoader loader = new FXMLLoader(getClass().getResource("MyFXML.fxml"));
    OwnController controller = loader.getController();
    controller.setStage(this.stage);
    
  3. Now you can access the stage in controller

Multiple queries executed in java in single statement

Based on my testing, the correct flag is "allowMultiQueries=true"

Using quotation marks inside quotation marks

You could do this in one of three ways:

  1. Use single and double quotes together:
    print('"A word that needs quotation marks"')
    "A word that needs quotation marks"
  1. Escape the double quotes within the string:
    print("\"A word that needs quotation marks\"")
    "A word that needs quotation marks" 
  1. Use triple-quoted strings:
    print(""" "A word that needs quotation marks" """)
    "A word that needs quotation marks" 

How to check if the docker engine and a docker container are running?

You can also check if a particular docker container is running or not using following command:

docker inspect postgres | grep "Running"

This command will check if for example my postgres container is running or not and will return output as "Running": true

Hope this helps.

JavaScript equivalent to printf/String.Format

Adding to zippoxer's answer, I use this function:

String.prototype.format = function () {
    var a = this, b;
    for (b in arguments) {
        a = a.replace(/%[a-z]/, arguments[b]);
    }
    return a; // Make chainable
};

var s = 'Hello %s The magic number is %d.';
s.format('world!', 12); // Hello World! The magic number is 12.

I also have a non-prototype version which I use more often for its Java-like syntax:

function format() {
    var a, b, c;
    a = arguments[0];
    b = [];
    for(c = 1; c < arguments.length; c++){
        b.push(arguments[c]);
    }
    for (c in b) {
        a = a.replace(/%[a-z]/, b[c]);
    }
    return a;
}
format('%d ducks, 55 %s', 12, 'cats'); // 12 ducks, 55 cats

ES 2015 update

All the cool new stuff in ES 2015 makes this a lot easier:

function format(fmt, ...args){
    return fmt
        .split("%%")
        .reduce((aggregate, chunk, i) =>
            aggregate + chunk + (args[i] || ""), "");
}

format("Hello %%! I ate %% apples today.", "World", 44);
// "Hello World, I ate 44 apples today."

I figured that since this, like the older ones, doesn't actually parse the letters, it might as well just use a single token %%. This has the benefit of being obvious and not making it difficult to use a single %. However, if you need %% for some reason, you would need to replace it with itself:

format("I love percentage signs! %%", "%%");
// "I love percentage signs! %%"

Exposing the current state name with ui router

this is how I do it

JAVASCRIPT:

var module = angular.module('yourModuleName', ['ui.router']);

module.run( ['$rootScope', '$state', '$stateParams',
                      function ($rootScope,   $state,   $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams; 
}
]);

HTML:

<pre id="uiRouterInfo">
      $state = {{$state.current.name}}
      $stateParams = {{$stateParams}}
      $state full url = {{ $state.$current.url.source }}    
</pre>

EXAMPLE

http://plnkr.co/edit/LGMZnj?p=preview

Get current cursor position in a textbox

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

_x000D_
_x000D_
function textbox()_x000D_
{_x000D_
        var ctl = document.getElementById('Javascript_example');_x000D_
        var startPos = ctl.selectionStart;_x000D_
        var endPos = ctl.selectionEnd;_x000D_
        alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
_x000D_
_x000D_

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

How to make HTML code inactive with comments

HTML Comments:

<!-- <div> This div will not show </div> -->

See Reference

CSS Comments:

/* This style will not apply */

See Reference

JavaScript Comments:

// This single line JavaScript code will not execute

OR

/*
   The whole block of JavaScript code will not execute
*/

See Reference

Check if Cell value exists in Column, and then get the value of the NEXT Cell

Use a different function, like VLOOKUP:

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", VLOOKUP(A1,B:C,2,FALSE))

ASP.NET: Session.SessionID changes between requests

In my case this was happening a lot in my development and test environments. After trying all of the above solutions without any success I found that I was able to fix this problem by deleting all session cookies. The web developer extension makes this very easy to do. I mostly use Firefox for testing and development, but this also happened while testing in Chrome. The fix also worked in Chrome.

I haven't had to do this yet in the production environment and have not received any reports of people not being able to log in. This also only seemed to happen after making the session cookies to be secure. It never happened in the past when they were not secure.

Select row and element in awk

To print the columns with a specific string, you use the // search pattern. For example, if you are looking for second columns that contains abc:

awk '$2 ~ /abc/'

... and if you want to print only a particular column:

awk '$2 ~ /abc/ { print $3 }'

... and for a particular line number:

awk '$2 ~ /abc/ && FNR == 5 { print $3 }'

Batch script to find and replace a string in text file within a minute for files up to 12 MB

How about this?

set search=%1
set replace=%2
set textfile=Input.txt    

python -c "with open('%textfile%', 'rw') as f: f.write(f.read().replace('%search%', '%replace%'))"

Muhahaha

Looking for a good Python Tree data structure

You can build a nice tree of dicts of dicts like this:

import collections

def Tree():
    return collections.defaultdict(Tree)

It might not be exactly what you want but it's quite useful! Values are saved only in the leaf nodes. Here is an example of how it works:

>>> t = Tree()
>>> t
defaultdict(<function tree at 0x2142f50>, {})
>>> t[1] = "value"
>>> t[2][2] = "another value"
>>> t
defaultdict(<function tree at 0x2142f50>, {1: 'value', 2: defaultdict(<function tree at 0x2142f50>, {2: 'another value'})}) 

For more information take a look at the gist.

Fastest check if row exists in PostgreSQL

INSERT INTO target( userid, rightid, count )
  SELECT userid, rightid, count 
  FROM batch
  WHERE NOT EXISTS (
    SELECT * FROM target t2, batch b2
    WHERE t2.userid = b2.userid
    -- ... other keyfields ...
    )       
    ;

BTW: if you want the whole batch to fail in case of a duplicate, then (given a primary key constraint)

INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count 
FROM batch
    ;

will do exactly what you want: either it succeeds, or it fails.

How can I view an old version of a file with Git?

You can use a script like this to dump all the versions of a file to separate files:

e.g.

git_dump_all_versions_of_a_file.sh path/to/somefile.txt

Get the script here as an answer to another similar question

How to serialize an object to XML without getting xmlns="..."?

I Suggest this helper class:

public static class Xml
{
    #region Fields

    private static readonly XmlWriterSettings WriterSettings = new XmlWriterSettings {OmitXmlDeclaration = true, Indent = true};
    private static readonly XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces(new[] {new XmlQualifiedName("", "")});

    #endregion

    #region Methods

    public static string Serialize(object obj)
    {
        if (obj == null)
        {
            return null;
        }

        return DoSerialize(obj);
    }

    private static string DoSerialize(object obj)
    {
        using (var ms = new MemoryStream())
        using (var writer = XmlWriter.Create(ms, WriterSettings))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj, Namespaces);
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }

    public static T Deserialize<T>(string data)
        where T : class
    {
        if (string.IsNullOrEmpty(data))
        {
            return null;
        }

        return DoDeserialize<T>(data);
    }

    private static T DoDeserialize<T>(string data) where T : class
    {
        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))
        {
            var serializer = new XmlSerializer(typeof (T));
            return (T) serializer.Deserialize(ms);
        }
    }

    #endregion
}

:)

Installing packages in Sublime Text 2

With Package Control in Sublime Text 2, you really need to become cozy with a couple of different things to make it all work:

  1. Always look up a package in the wbond community. There you'll be able to see how many people have installed that package (the more popular, the better) as well as the documentation on the package (if any).
  2. Menu Items under Prefs > Package Control. Here you can install, remove or see a list of all installed packages.
  3. Prefs > Package Settings. Here you'll find the settings that can be tinkered with as well as shortcut keys that are available. Make sure to make any changes in the User Settings, rather than the Default Settings. Otherwise, your settings will be overwritten when that package is updated.
  4. CTRL+SHIFT+P. This will bring up a menu where you can look up a lot of the functions your installed packages can do. Just start typing and it will start filtering.

Add items in array angular 4

Yes there is a way to do it.

First declare a class.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

Then in your component import the class

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html

Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

For me the problem was that I was using different versions of Python in the same Eclipse project. My setup was not consistent with the Project Properties and the Run Configuration Python versions.

In Project > Properties > PyDev, I had the Interpreter set to Python2.7.11.

In Run Configurations > Interpreter, I was using the Default Interpreter. Changing it to Python 2.7.11 fixed the problem.

What is the default Jenkins password?

On ubuntu 19.04, the default password are stored in the home directory:

cat ~/.jenkins/secrets/initialAdminPassword

functional way to iterate over range (ES6/7)

Here's an approach using generators:

function* square(n) {
    for (var i = 0; i < n; i++ ) yield i*i;
}

Then you can write

console.log(...square(7));

Another idea is:

[...Array(5)].map((_, i) => i*i)

Array(5) creates an unfilled five-element array. That's how Array works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.

Alternatively, we could write

Array.from(Array(5)).map((_, i) => i*i)

or, we could take advantage of the second argument to Array#from to skip the map and write

Array.from(Array(5), (_, i) => i*i)

A horrible hack which I saw recently, which I do not recommend you use, is

[...1e4+''].map((_, i) => i*i)

Rendering JSON in controller

For the instance of

render :json => @projects, :include => :tasks

You are stating that you want to render @projects as JSON, and include the association tasks on the Project model in the exported data.

For the instance of

render :json => @projects, :callback => 'updateRecordDisplay'

You are stating that you want to render @projects as JSON, and wrap that data in a javascript call that will render somewhat like:

updateRecordDisplay({'projects' => []})

This allows the data to be sent to the parent window and bypass cross-site forgery issues.

How do I tokenize a string in C++?

I made a lexer/tokenizer before with the use of only standard libraries. Here's the code:

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

string seps(string& s) {
    if (!s.size()) return "";
    stringstream ss;
    ss << s[0];
    for (int i = 1; i < s.size(); i++) {
        ss << '|' << s[i];
    }
    return ss.str();
}

void Tokenize(string& str, vector<string>& tokens, const string& delimiters = " ")
{
    seps(str);

    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos = str.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}

int main(int argc, char *argv[])
{
    vector<string> t;
    string s = "Tokens for everyone!";

    Tokenize(s, t, "|");

    for (auto c : t)
        cout << c << endl;

    system("pause");

    return 0;
}

Pass arguments into C program from command line

Consider using getopt_long(). It allows both short and long options in any combination.

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

/* Flag set by `--verbose'. */
static int verbose_flag;

int
main (int argc, char *argv[])
{
  while (1)
    {
      static struct option long_options[] =
    {
      /* This option set a flag. */
      {"verbose", no_argument,       &verbose_flag, 1},
      /* These options don't set a flag.
         We distinguish them by their indices. */
      {"blip",    no_argument,       0, 'b'},
      {"slip",    no_argument,       0, 's'},
      {0,         0,                 0,  0}
    };
      /* getopt_long stores the option index here. */
      int option_index = 0;

      int c = getopt_long (argc, argv, "bs",
               long_options, &option_index);

      /* Detect the end of the options. */
      if (c == -1)
    break;

      switch (c)
    {
    case 0:
      /* If this option set a flag, do nothing else now. */
      if (long_options[option_index].flag != 0)
        break;
      printf ("option %s", long_options[option_index].name);
      if (optarg)
        printf (" with arg %s", optarg);
      printf ("\n");
      break;
    case 'b':
      puts ("option -b\n");
      break;
    case 's':
      puts ("option -s\n");
      break;
    case '?':
      /* getopt_long already printed an error message. */
      break;

    default:
      abort ();
    }
    }

  if (verbose_flag)
    puts ("verbose flag is set");

  /* Print any remaining command line arguments (not options). */
  if (optind < argc)
    {
      printf ("non-option ARGV-elements: ");
      while (optind < argc)
    printf ("%s ", argv[optind++]);
      putchar ('\n');
    }

  return 0;
}

Related:

Launch Bootstrap Modal on page load

Update 2020 - Bootstrap 5

Building on the excellent responses from previous answers, in Bootstrap 5 with no jQuery, this has worked;

document.querySelector('[data-target="#exampleModal"]').click();

Full snippet:

_x000D_
_x000D_
window.onload = () => {
  document.querySelector('[data-target="#exampleModal"]').click();
}
_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" rel="stylesheet" />


<div class="container py-3">

  <!-- Button trigger modal -->
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
    Launch demo modal
  </button>

  <!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>

</div>
_x000D_
_x000D_
_x000D_

What is mod_php?

Your server needs to have the php modules installed so it can parse php code.

If you are on ubuntu you can do this easily with

sudo apt-get install apache2

sudo apt-get install php5

sudo apt-get install libapache2-mod-php5

sudo /etc/init.d/apache2 restart

Otherwise you may compile apache with php: http://dan.drydog.com/apache2php.html

Specifying your server OS will help others to answer more specifically.

Is Django for the frontend or backend?

(a) Django is a framework, not a language

(b) I'm not sure what you're missing - there is no reason why you can't have business logic in a web application. In Django, you would normally expect presentation logic to be separated from business logic. Just because it is hosted in the same application server, it doesn't follow that the two layers are entangled.

(c) Django does provide templating, but it doesn't provide rich libraries for generating client-side content.

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

A 64-bit version of the 'Microsoft Access Database Engine 2010 Redistributable' that will allow you to use the 'Microsoft.ACE.OLEDB.12.0' provider is available here:
http://www.microsoft.com/en-us/download/details.aspx?id=13255

If you use the download from the accepted answer, you will need to build for x86, as pointed out by @backtestbroker.com.

Should operator<< be implemented as a friend or as a member function?

friend operator = equal rights as class

friend std::ostream& operator<<(std::ostream& os, const Object& object) {
    os << object._atribute1 << " " << object._atribute2 << " " << atribute._atribute3 << std::endl;
    return os;
}

Git push failed, "Non-fast forward updates were rejected"

Sometimes, while taking a pull from your git, the HEAD gets detached. You can check this by entering the command:

git branch 
  • (HEAD detached from 8790704)

    master

    develop

It's better to move to your branch and take a fresh pull from your respective branch.

git checkout develop

git pull origin develop

git push origin develop

Show Youtube video source into HTML5 video tag?

With the new iframe tag embedded in your website, the code will automatically detect whether you are using a browser that supports HTML5 or not.

The iframe code for embedding YouTube videos is as follows, simply copy the Video ID and replace in the code below:

<iframe type="text/html" 
    width="640" 
    height="385" 
    src="http://www.youtube.com/embed/VIDEO_ID"
    frameborder="0">
</iframe>

Is there a MySQL option/feature to track history of changes to records?

Here's a straightforward way to do this:

First, create a history table for each data table you want to track (example query below). This table will have an entry for each insert, update, and delete query performed on each row in the data table.

The structure of the history table will be the same as the data table it tracks except for three additional columns: a column to store the operation that occured (let's call it 'action'), the date and time of the operation, and a column to store a sequence number ('revision'), which increments per operation and is grouped by the primary key column of the data table.

To do this sequencing behavior a two column (composite) index is created on the primary key column and revision column. Note that you can only do sequencing in this fashion if the engine used by the history table is MyISAM (See 'MyISAM Notes' on this page)

The history table is fairly easy to create. In the ALTER TABLE query below (and in the trigger queries below that), replace 'primary_key_column' with the actual name of that column in your data table.

CREATE TABLE MyDB.data_history LIKE MyDB.data;

ALTER TABLE MyDB.data_history MODIFY COLUMN primary_key_column int(11) NOT NULL, 
   DROP PRIMARY KEY, ENGINE = MyISAM, ADD action VARCHAR(8) DEFAULT 'insert' FIRST, 
   ADD revision INT(6) NOT NULL AUTO_INCREMENT AFTER action,
   ADD dt_datetime DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER revision,
   ADD PRIMARY KEY (primary_key_column, revision);

And then you create the triggers:

DROP TRIGGER IF EXISTS MyDB.data__ai;
DROP TRIGGER IF EXISTS MyDB.data__au;
DROP TRIGGER IF EXISTS MyDB.data__bd;

CREATE TRIGGER MyDB.data__ai AFTER INSERT ON MyDB.data FOR EACH ROW
    INSERT INTO MyDB.data_history SELECT 'insert', NULL, NOW(), d.* 
    FROM MyDB.data AS d WHERE d.primary_key_column = NEW.primary_key_column;

CREATE TRIGGER MyDB.data__au AFTER UPDATE ON MyDB.data FOR EACH ROW
    INSERT INTO MyDB.data_history SELECT 'update', NULL, NOW(), d.*
    FROM MyDB.data AS d WHERE d.primary_key_column = NEW.primary_key_column;

CREATE TRIGGER MyDB.data__bd BEFORE DELETE ON MyDB.data FOR EACH ROW
    INSERT INTO MyDB.data_history SELECT 'delete', NULL, NOW(), d.* 
    FROM MyDB.data AS d WHERE d.primary_key_column = OLD.primary_key_column;

And you're done. Now, all the inserts, updates and deletes in 'MyDb.data' will be recorded in 'MyDb.data_history', giving you a history table like this (minus the contrived 'data_columns' column)

ID    revision   action    data columns..
1     1         'insert'   ....          initial entry for row where ID = 1
1     2         'update'   ....          changes made to row where ID = 1
2     1         'insert'   ....          initial entry, ID = 2
3     1         'insert'   ....          initial entry, ID = 3 
1     3         'update'   ....          more changes made to row where ID = 1
3     2         'update'   ....          changes made to row where ID = 3
2     2         'delete'   ....          deletion of row where ID = 2 

To display the changes for a given column or columns from update to update, you'll need to join the history table to itself on the primary key and sequence columns. You could create a view for this purpose, for example:

CREATE VIEW data_history_changes AS 
   SELECT t2.dt_datetime, t2.action, t1.primary_key_column as 'row id', 
   IF(t1.a_column = t2.a_column, t1.a_column, CONCAT(t1.a_column, " to ", t2.a_column)) as a_column
   FROM MyDB.data_history as t1 INNER join MyDB.data_history as t2 on t1.primary_key_column = t2.primary_key_column 
   WHERE (t1.revision = 1 AND t2.revision = 1) OR t2.revision = t1.revision+1
   ORDER BY t1.primary_key_column ASC, t2.revision ASC

Edit: Oh wow, people like my history table thing from 6 years ago :P

My implementation of it is still humming along, getting bigger and more unwieldy, I would assume. I wrote views and pretty nice UI to look at the history in this database, but I don't think it was ever used much. So it goes.

To address some comments in no particular order:

  • I did my own implementation in PHP that was a little more involved, and avoided some of the problems described in comments (having indexes transferred over, signifcantly. If you transfer over unique indexes to the history table, things will break. There are solutions for this in the comments). Following this post to the letter could be an adventure, depending on how established your database is.

  • If the relationship between the primary key and the revision column seems off it usually means the composite key is borked somehow. On a few rare occasions I had this happen and was at a loss to the cause.

  • I found this solution to be pretty performant, using triggers as it does. Also, MyISAM is fast at inserts, which is all the triggers do. You can improve this further with smart indexing (or lack of...). Inserting a single row into a MyISAM table with a primary key shouldn't be an operation you need to optimize, really, unless you have significant issues going on elsewhere. In the entire time I was running the MySQL database this history table implementation was on, it was never the cause of any of the (many) performance problems that came up.

  • if you're getting repeated inserts, check your software layer for INSERT IGNORE type queries. Hrmm, can't remember now, but I think there are issues with this scheme and transactions which ultimately fail after running multiple DML actions. Something to be aware of, at least.

  • It's important that the fields in the history table and the data table match up. Or, rather, that your data table doesn't have MORE columns than the history table. Otherwise, insert/update/del queries on the data table will fail, when the inserts to the history tables put columns in the query that don't exist (due to d.* in the trigger queries), and the trigger fails. t would be awesome if MySQL had something like schema-triggers, where you could alter the history table if columns were added to the data table. Does MySQL have that now? I do React these days :P

Android Studio - Importing external Library/Jar

I'm using Android Studio 0.5.2. So if your version is lower than mine my answer may not work for you.

3 ways to add a new Jar to your project:

  1. Menu under Files-->Project Structure
  2. Just press 'F4'
  3. under Project navigation, right clink on any java library and a context menu will show then click on 'Open Library Settings'

A Project Structure window will popup.

On the left column click on 'Libraries' then look at the right pane where there is a plus sign '+' and click on it then enter the path to your new library.

Make sure the new library is under the 'project\libs\' folder otherwise you may get a broken link when you save your project source code.

How do I convert a dictionary to a JSON String in C#?

Just for reference, among all the older solutions: UWP has its own built-in JSON library, Windows.Data.Json.

JsonObject is a map that you can use directly to store your data:

var options = new JsonObject();
options["foo"] = JsonValue.CreateStringValue("bar");
string json = options.ToString();

How to permanently remove few commits from remote branch

This might be too little too late but what helped me is the cool sounding 'nuclear' option. Basically using the command filter-branch you can remove files or change something over a large number of files throughout your entire git history.

It is best explained here.

continuing execution after an exception is thrown in java

Try this:

try
{
    throw new InvalidEmployeeTypeException();
    input.nextLine();
}
catch(InvalidEmployeeTypeException ex)
{
      //do error handling
}

continue;

Photoshop text tool adds punctuation to the beginning of text

You can try : go to edit>preferencec>type.. select type > choose text engine options select east asian. Restart photoshop. Create new peroject. Try text tool again.

(if you want to use your project created with other text engine type) copy /paste all layers to new project.

Label axes on Seaborn Barplot

One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

Solution code:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

Output figure:

enter image description here

Change an image with onclick()

If you don't want use js, I think, you can use <a href="javascript:void(0);"></a> instead of img and then use css like

a {
  background: url('oldImage.png');
}
a:visited {
  background: url('newImage.png');
}

EDIT: Nope. Sorry it works only for :hover

How To Add An "a href" Link To A "div"?

In this case, it doesn't matter as there is no content between the two divs.

Either one will get the browser to scroll down to it.

The a element will look like:

<a href="mypageName.html#buttonOne">buttonOne</a>

Or:

<a href="mypageName.html#linkedinB">linkedinB</a>

Can I invoke an instance method on a Ruby module without including it?

After almost 9 years here's a generic solution:

module CreateModuleFunctions
  def self.included(base)
    base.instance_methods.each do |method|
      base.module_eval do
        module_function(method)
        public(method)
      end
    end
  end
end

RSpec.describe CreateModuleFunctions do
  context "when included into a Module" do
    it "makes the Module's methods invokable via the Module" do
      module ModuleIncluded
        def instance_method_1;end
        def instance_method_2;end

        include CreateModuleFunctions
      end

      expect { ModuleIncluded.instance_method_1 }.to_not raise_error
    end
  end
end

The unfortunate trick you need to apply is to include the module after the methods have been defined. Alternatively you may also include it after the context is defined as ModuleIncluded.send(:include, CreateModuleFunctions).

Or you can use it via the reflection_utils gem.

spec.add_dependency "reflection_utils", ">= 0.3.0"

require 'reflection_utils'
include ReflectionUtils::CreateModuleFunctions

Submit form on pressing Enter with AngularJS

Another approach would be using ng-keypress ,

<input type="text" ng-model="data" ng-keypress="($event.charCode==13)? myfunc() : return"> 

Submit an input on pressing Enter with AngularJS - jsfiddle

How to connect mySQL database using C++

I had to include -lmysqlcppconn to my build in order to get it to work.

How to format a float in javascript?

var result = Math.round(original*100)/100;

The specifics, in case the code isn't self-explanatory.

edit: ...or just use toFixed, as proposed by Tim Büthe. Forgot that one, thanks (and an upvote) for reminder :)

The view or its master was not found or no view engine supports the searched locations

This could be a permissions issue.

I had the same issue recently. As a test, I created a simple hello.html page. When I tried loading it, I got an error message regarding permissions. Once I fixed the permissions issue in the root web folder, both the html page and the MVC rendering issues were resolved.

Add an object to a python list

If i am correct in believing that you are adding a variable to the array but when you change that variable outside of the array, it also changes inside the array but you don't want it to then it is a really simple solution.

When you are saving the variable to the array you should turn it into a string by simply putting str(variablename). For example:

array.append(str(variablename))

Using this method your code should look like this:

arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(str(wM))        #this is the only line that is changed.
    wM.reset()

How to convert a date to milliseconds

The 2017 answer is: Use the date and time classes introduced in Java 8 (and also backported to Java 6 and 7 in the ThreeTen Backport).

If you want to interpret the date-time string in the computer’s time zone:

    long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
            .atZone(ZoneId.systemDefault())
            .toInstant()
            .toEpochMilli();

If another time zone, fill that zone in instead of ZoneId.systemDefault(). If UTC, use

    long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
            .atOffset(ZoneOffset.UTC)
            .toInstant()
            .toEpochMilli();

adding text to an existing text element in javascript via DOM

The reason that appendChild is not a function is because you're executing it on the textContent of your p element.

You instead just need to select the paragraph itself, and then append your new text node to that:

_x000D_
_x000D_
var paragraph = document.getElementById("p");_x000D_
var text = document.createTextNode("This just got added");_x000D_
_x000D_
paragraph.appendChild(text);
_x000D_
<p id="p">This is some text</p>
_x000D_
_x000D_
_x000D_

However instead, if you like, you can just modify the text itself (rather than adding a new node):

_x000D_
_x000D_
var paragraph = document.getElementById("p");_x000D_
_x000D_
paragraph.textContent += "This just got added";
_x000D_
<p id="p">This is some text</p>
_x000D_
_x000D_
_x000D_

Dataset - Vehicle make/model/year (free)

How about Freebase? I think they have an API available, too.

http://www.freebase.com/

Drawing an SVG file on a HTML5 canvas

Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"

"Insufficient Storage Available" even there is lot of free space in device memory

Go to Settings, Apps, All and uninstall Google Play Store. This will replace by the old version and then you can download without the "Insufficient Storage ERROR" It works for me

How to stop console from closing on exit?

Add a Console.ReadKey call to your program to force it to wait for you to press a key before exiting.

android:layout_height 50% of the screen size

This is easy to do in xml. Set your top container to be a LinearLayout and set the orientation attribute as you wish. Then inside of that place two linearlayouts that both have "fill parent" on width and height. Finally, set the weigth attribute of those two linearlayouts to 1.

How to find the process id of a running Java process on Windows? And how to kill the process alone?

You can use the jps utility that is included in the JDK to find the process id of a Java process. The output will show you the name of the executable JAR file or the name of the main class.

Then use the Windows task manager to terminate the process. If you want to do it on the command line, use

TASKKILL /PID %PID%

Installing and Running MongoDB on OSX

Download MongoDB and install it on your local machine. Link https://www.mongodb.com/try/download/enterprise

Extract the file and put it on the desktop. Create another folder where you want to store the data. I have created mongodb-data folder. Then run the below command.

Desktop/mongodb/bin/mongod --dbpath=/Users/yourname/Desktop/mongodb-data/

Before the hyphen is the executable path of your mongoDB and after hyphen is your data store.

java.io.FileNotFoundException: (Access is denied)

Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.

It worked for me so here's hoping it helps someone else, too.

get the selected index value of <select> tag in php

Your form is valid. Only thing that comes to my mind is, after seeing your full html, is that you're passing your "default" value (which is not set!) instead of selecting something. Try as suggested by @Vina in the comment, i.e. giving it a selected option, or writing a default value

<select name="gender">
<option value="default">Select </option>    
<option value="male">   Male   </option>
<option value="female"> Female </option>
</select>

OR

<select name="gender">
<option value="male" selected="selected">   Male   </option>
<option value="female"> Female </option>
</select>

When you get your $_POST vars, check for them being set; you can assign a default value, or just an empty string in case they're not there.

Most important thing, AVOID SQL INJECTIONS:

//....
$fname   = isset($_POST["fname"]) ? mysql_real_escape_string($_POST['fname']) : '';
$lname   = isset($_POST['lname']) ? mysql_real_escape_string($_POST['lname']) : '';
$email   = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : '';
you might also want to validate e-mail:
if($mail = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
  $email = mysql_real_escape_string($_POST['email']);
}
else
{
  //die ('invalid email address');
  // or whatever, a default value? $email = '';
}
$paswod  = isset($_POST["paswod"]) ? mysql_real_escape_string($_POST['paswod']) : '';
$gender  = isset($_POST['gender']) ? mysql_real_escape_string($_POST['gender']) : '';

$query = mysql_query("SELECT Email FROM users WHERE Email = '".$email."')";
if(mysql_num_rows($query)> 0)
{
  echo 'userid is already there';
}
else
{
 $sql = "INSERT INTO users (FirstName, LastName, Email, Password, Gender)
         VALUES ('".$fname."','".$lname."','".$email."','".paswod."','".$gender."')";
$res = mysql_query($sql) or die('Error:'.mysql_error());
echo 'created';

What does AND 0xFF do?

The danger of the second expression comes if the type of byte1 is char. In that case, some implementations can have it signed char, which will result in sign extension when evaluating.

signed char byte1 = 0x80;
signed char byte2 = 0x10;

unsigned short value1 = ((byte2 << 8) | (byte1 & 0xFF));
unsigned short value2 = ((byte2 << 8) | byte1);

printf("value1=%hu %hx\n", value1, value1);
printf("value2=%hu %hx\n", value2, value2);

will print

value1=4224 1080     right
value2=65408 ff80    wrong!!

I tried it on gcc v3.4.6 on Solaris SPARC 64 bit and the result is the same with byte1 and byte2 declared as char.

TL;DR

The masking is to avoid implicit sign extension.

EDIT: I checked, it's the same behaviour in C++.

EDIT2: As requested explanation of sign extension. Sign extension is a consequence of the way C evaluates expressions. There is a rule in C called promotion rule. C will implicitly cast all small types to int before doing the evaluation. Let's see what happens to our expression:

unsigned short value2 = ((byte2 << 8) | byte1);

byte1 is a variable containing bit pattern 0xFF. If char is unsigned that value is interpreted as 255, if it is signed it is -128. When doing the calculation, C will extend the value to an int size (16 or 32 bits generally). This means that if the variable is unsigned and we will keep the value 255, the bit-pattern of that value as int will be 0x000000FF. If it is signed we want the value -128 which bit pattern is 0xFFFFFFFF. The sign was extended to the size of the tempory used to do the calculation. And thus oring the temporary will yield the wrong result.

On x86 assembly it is done with the movsx instruction (movzx for the zero extend). Other CPU's had other instructions for that (6809 had SEX).

Am I trying to connect to a TLS-enabled daemon without TLS?

I faced the same issue when I was creating Docker images from Jenkins. Simply add the user to the docker group and then restart Docker services and in my case I had to restart Jenkins services.

This was the error which I got:

http:///var/run/docker.sock/v1.19/build?cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&memory=0&memswap=0&rm=1&t=59aec062a8dd8b579ee1b61b299e1d9d340a1340: dial unix /var/run/docker.sock: permission denied. Are you trying to connect to a TLS-enabled daemon without TLS?
FATAL: Failed to build docker image from project Dockerfile
java.lang.RuntimeException: Failed to build docker image from project Dockerfile

Solution:

[root@Jenkins ssh]# groupadd docker
[root@Jenkins ssh]# gpasswd -a jenkins docker
Adding user jenkins to group docker
[root@Jenkins ssh]# /etc/init.d/docker restart
Stopping docker:                                           [  OK  ]
Starting docker:                                           [  OK  ]
[root@Jenkins ssh]# /etc/init.d/jenkins restart
Shutting down Jenkins                                      [  OK  ]
Starting Jenkins                                           [  OK  ]
[root@Jenkins ssh]#

Creating the Singleton design pattern in PHP5

Unfortunately Inwdr's answer breaks when there are multiple subclasses.

Here is a correct inheritable Singleton base class.

class Singleton
{
    private static $instances = array();
    protected function __construct() {}
    protected function __clone() {}
    public function __wakeup()
    {
        throw new Exception("Cannot unserialize singleton");
    }

    public static function getInstance()
    {
        $cls = get_called_class(); // late-static-bound class name
        if (!isset(self::$instances[$cls])) {
            self::$instances[$cls] = new static;
        }
        return self::$instances[$cls];
    }
}

Test code:

class Foo extends Singleton {}
class Bar extends Singleton {}

echo get_class(Foo::getInstance()) . "\n";
echo get_class(Bar::getInstance()) . "\n";

Producer/Consumer threads using a Queue

This is a very simple code.

import java.util.*;

// @author : rootTraveller, June 2017

class ProducerConsumer {
    public static void main(String[] args) throws Exception {
        Queue<Integer> queue = new LinkedList<>();
        Integer buffer = new Integer(10);  //Important buffer or queue size, change as per need.

        Producer producerThread = new Producer(queue, buffer, "PRODUCER");
        Consumer consumerThread = new Consumer(queue, buffer, "CONSUMER");

        producerThread.start();  
        consumerThread.start();
    }   
}

class Producer extends Thread {
    private Queue<Integer> queue;
    private int queueSize ;

    public Producer (Queue<Integer> queueIn, int queueSizeIn, String ThreadName){
        super(ThreadName);
        this.queue = queueIn;
        this.queueSize = queueSizeIn;
    }

    public void run() {
        while(true){
            synchronized (queue) {
                while(queue.size() == queueSize){
                    System.out.println(Thread.currentThread().getName() + " FULL         : waiting...\n");
                    try{
                        queue.wait();   //Important
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

                //queue empty then produce one, add and notify  
                int randomInt = new Random().nextInt(); 
                System.out.println(Thread.currentThread().getName() + " producing... : " + randomInt); 
                queue.add(randomInt); 
                queue.notifyAll();  //Important
            } //synchronized ends here : NOTE
        }
    }
}

class Consumer extends Thread {
    private Queue<Integer> queue;
    private int queueSize;

    public Consumer(Queue<Integer> queueIn, int queueSizeIn, String ThreadName){
        super (ThreadName);
        this.queue = queueIn;
        this.queueSize = queueSizeIn;
    }

    public void run() {
        while(true){
            synchronized (queue) {
                while(queue.isEmpty()){
                    System.out.println(Thread.currentThread().getName() + " Empty        : waiting...\n");
                    try {
                        queue.wait();  //Important
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

                //queue not empty then consume one and notify
                System.out.println(Thread.currentThread().getName() + " consuming... : " + queue.remove());
                queue.notifyAll();
            } //synchronized ends here : NOTE
        }
    }
}

How do I convert a javascript object array to a string array of the object attribute I want?

If your array of objects is items, you can do:

_x000D_
_x000D_
var items = [{_x000D_
  id: 1,_x000D_
  name: 'john'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'jane'_x000D_
}, {_x000D_
  id: 2000,_x000D_
  name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
  return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

Documentation: map()

How to convert a char array to a string?

Another solution might look like this,

char arr[] = "mom";
std::cout << "hi " << std::string(arr);

which avoids using an extra variable.

Do I need to close() both FileReader and BufferedReader?

no.

BufferedReader.close()

closes the stream according to javadoc for BufferedReader and InputStreamReader

as well as

FileReader.close()

does.

How to start a background process in Python?

You probably want to start investigating the os module for forking different threads (by opening an interactive session and issuing help(os)). The relevant functions are fork and any of the exec ones. To give you an idea on how to start, put something like this in a function that performs the fork (the function needs to take a list or tuple 'args' as an argument that contains the program's name and its parameters; you may also want to define stdin, out and err for the new thread):

try:
    pid = os.fork()
except OSError, e:
    ## some debug output
    sys.exit(1)
if pid == 0:
    ## eventually use os.putenv(..) to set environment variables
    ## os.execv strips of args[0] for the arguments
    os.execv(args[0], args)

RESTful Authentication via Spring

We managed to get this working exactly as described in the OP, and hopefully someone else can make use of the solution. Here's what we did:

Set up the security context like so:

<security:http realm="Protected API" use-expressions="true" auto-config="false" create-session="stateless" entry-point-ref="CustomAuthenticationEntryPoint">
    <security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
    <security:intercept-url pattern="/authenticate" access="permitAll"/>
    <security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>

<bean id="CustomAuthenticationEntryPoint"
    class="com.demo.api.support.spring.CustomAuthenticationEntryPoint" />

<bean id="authenticationTokenProcessingFilter"
    class="com.demo.api.support.spring.AuthenticationTokenProcessingFilter" >
    <constructor-arg ref="authenticationManager" />
</bean>

As you can see, we've created a custom AuthenticationEntryPoint, which basically just returns a 401 Unauthorized if the request wasn't authenticated in the filter chain by our AuthenticationTokenProcessingFilter.

CustomAuthenticationEntryPoint:

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Authentication token was either missing or invalid." );
    }
}

AuthenticationTokenProcessingFilter:

public class AuthenticationTokenProcessingFilter extends GenericFilterBean {

    @Autowired UserService userService;
    @Autowired TokenUtils tokenUtils;
    AuthenticationManager authManager;

    public AuthenticationTokenProcessingFilter(AuthenticationManager authManager) {
        this.authManager = authManager;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        @SuppressWarnings("unchecked")
        Map<String, String[]> parms = request.getParameterMap();

        if(parms.containsKey("token")) {
            String token = parms.get("token")[0]; // grab the first "token" parameter

            // validate the token
            if (tokenUtils.validate(token)) {
                // determine the user based on the (already validated) token
                UserDetails userDetails = tokenUtils.getUserFromToken(token);
                // build an Authentication object with the user's info
                UsernamePasswordAuthenticationToken authentication = 
                        new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
                // set the authentication into the SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(authentication));         
            }
        }
        // continue thru the filter chain
        chain.doFilter(request, response);
    }
}

Obviously, TokenUtils contains some privy (and very case-specific) code and can't be readily shared. Here's its interface:

public interface TokenUtils {
    String getToken(UserDetails userDetails);
    String getToken(UserDetails userDetails, Long expiration);
    boolean validate(String token);
    UserDetails getUserFromToken(String token);
}

That ought to get you off to a good start. Happy coding. :)

Using SUMIFS with multiple AND OR conditions

In order to get the formula to work place the cursor inside the formula and press ctr+shift+enter and then it will work!

Calling multiple JavaScript functions on a button click

  <asp:Button ID="btnSubmit" runat="server"  OnClientClick ="showDiv()"
   OnClick="btnImport_Click" Text="Upload" ></asp:Button>

DropdownList DataSource

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        drpCategory.DataSource = CategoryHelper.Categories;
        drpCategory.DataTextField = "Name";
        drpCategory.DataValueField = "Id";
        drpCategory.DataBind();
    }
}

Switch to selected tab by name in Jquery-UI Tabs

Set specific tab index as active:

$(this).tabs({ active: # }); /* Where # is the tab index. The index count starts at 0 */

Set last tab as active

$(this).tabs({ active: -1 });

Set specific tab by ID:

$(this).tabs({ active: $('a[href="#tab-101"]').parent().index() });

What is the difference between XAMPP or WAMP Server & IIS?

XAMPP and WAMP are both web server applications for PHP and MYSQL with the apache server. When we consider IIS, it also a web-server like apache runs on windows only.

XWAMPP/WAMP - Windows,Apache,Mysql,PHP

IIS - Apache,SQL Server, ASP.NET

If you like to read more about XWAMPP vs WAMP

Error: expected type-specifier before 'ClassName'

First of all, let's try to make your code a little simpler:

// No need to create a circle unless it is clearly necessary to
// demonstrate the problem

// Your Rect2f defines a default constructor, so let's use it for simplicity.
shared_ptr<Shape> rect(new Rect2f());

Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:

int main() {
    delete new T();
}

This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:

In function 'int main()':
Line 2: error: expected type-specifier before 'T'

Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f.

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.