Programs & Examples On #Pmd

PMD scans source code and looks for potential problems like possible bugs, dead code, suboptimal code, overcomplicated expressions, and duplicate code. PMD supports Java, JavaScript, XML, and many more.

Avoid printStackTrace(); use a logger call instead

In Simple,e.printStackTrace() is not good practice,because it just prints out the stack trace to standard error. Because of this you can't really control where this output goes.

RegExp matching string not starting with my

^(?!my)\w+$

should work.

It first ensures that it's not possible to match my at the start of the string, and then matches alphanumeric characters until the end of the string. Whitespace anywhere in the string will cause the regex to fail. Depending on your input you might want to either strip whitespace in the front and back of the string before passing it to the regex, or use add optional whitespace matchers to the regex like ^\s*(?!my)(\w+)\s*$. In this case, backreference 1 will contain the name of the variable.

And if you need to ensure that your variable name starts with a certain group of characters, say [A-Za-z_], use

^(?!my)[A-Za-z_]\w*$

Note the change from + to *.

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

I do not have a PhD, nor any other kind of degree neither in CS nor math nor indeed any other field. I have no prior experience with Scala nor any other similar language. I have no experience with even remotely comparable type systems. In fact, the only language that I have more than just a superficial knowledge of which even has a type system is Pascal, not exactly known for its sophisticated type system. (Although it does have range types, which AFAIK pretty much no other language has, but that isn't really relevant here.) The other three languages I know are BASIC, Smalltalk and Ruby, none of which even have a type system.

And yet, I have no trouble at all understanding the signature of the map function you posted. It looks to me like pretty much the same signature that map has in every other language I have ever seen. The difference is that this version is more generic. It looks more like a C++ STL thing than, say, Haskell. In particular, it abstracts away from the concrete collection type by only requiring that the argument is IterableLike, and also abstracts away from the concrete return type by only requiring that an implicit conversion function exists which can build something out of that collection of result values. Yes, that is quite complex, but it really is only an expression of the general paradigm of generic programming: do not assume anything that you don't actually have to.

In this case, map does not actually need the collection to be a list, or being ordered or being sortable or anything like that. The only thing that map cares about is that it can get access to all elements of the collection, one after the other, but in no particular order. And it does not need to know what the resulting collection is, it only needs to know how to build it. So, that is what its type signature requires.

So, instead of

map :: (a ? b) ? [a] ? [b]

which is the traditional type signature for map, it is generalized to not require a concrete List but rather just an IterableLike data structure

map :: (IterableLike i, IterableLike j) ? (a ? b) ? i ? j

which is then further generalized by only requiring that a function exists that can convert the result to whatever data structure the user wants:

map :: IterableLike i ? (a ? b) ? i ? ([b] ? c) ? c

I admit that the syntax is a bit clunkier, but the semantics are the same. Basically, it starts from

def map[B](f: (A) ? B): List[B]

which is the traditional signature for map. (Note how due to the object-oriented nature of Scala, the input list parameter vanishes, because it is now the implicit receiver parameter that every method in a single-dispatch OO system has.) Then it generalized from a concrete List to a more general IterableLike

def map[B](f: (A) ? B): IterableLike[B]

Now, it replaces the IterableLike result collection with a function that produces, well, really just about anything.

def map[B, That](f: A ? B)(implicit bf: CanBuildFrom[Repr, B, That]): That

Which I really believe is not that hard to understand. There's really only a couple of intellectual tools you need:

  1. You need to know (roughly) what map is. If you gave only the type signature without the name of the method, I admit, it would be a lot harder to figure out what is going on. But since you already know what map is supposed to do, and you know what its type signature is supposed to be, you can quickly scan the signature and focus on the anomalies, like "why does this map take two functions as arguments, not one?"
  2. You need to be able to actually read the type signature. But even if you have never seen Scala before, this should be quite easy, since it really is just a mixture of type syntaxes you already know from other languages: VB.NET uses square brackets for parametric polymorphism, and using an arrow to denote the return type and a colon to separate name and type, is actually the norm.
  3. You need to know roughly what generic programming is about. (Which isn't that hard to figure out, since it's basically all spelled out in the name: it's literally just programming in a generic fashion).

None of these three should give any professional or even hobbyist programmer a serious headache. map has been a standard function in pretty much every language designed in the last 50 years, the fact that different languages have different syntax should be obvious to anyone who has designed a website with HTML and CSS and you can't subscribe to an even remotely programming related mailinglist without some annoying C++ fanboy from the church of St. Stepanov explaining the virtues of generic programming.

Yes, Scala is complex. Yes, Scala has one of the most sophisticated type systems known to man, rivaling and even surpassing languages like Haskell, Miranda, Clean or Cyclone. But if complexity were an argument against success of a programming language, C++ would have died long ago and we would all be writing Scheme. There are lots of reasons why Scala will very likely not be successful, but the fact that programmers can't be bothered to turn on their brains before sitting down in front of the keyboard is probably not going to be the main one.

How to programmatically disable page scrolling with jQuery

you can use this code:

$("body").css("overflow", "hidden");

Fastest way to check if a value exists in a list

This is not the code, but the algorithm for very fast searching.

If your list and the value you are looking for are all numbers, this is pretty straightforward. If strings: look at the bottom:

  • -Let "n" be the length of your list
  • -Optional step: if you need the index of the element: add a second column to the list with current index of elements (0 to n-1) - see later
  • Order your list or a copy of it (.sort())
  • Loop through:
    • Compare your number to the n/2th element of the list
      • If larger, loop again between indexes n/2-n
      • If smaller, loop again between indexes 0-n/2
      • If the same: you found it
  • Keep narrowing the list until you have found it or only have 2 numbers (below and above the one you are looking for)
  • This will find any element in at most 19 steps for a list of 1.000.000 (log(2)n to be precise)

If you also need the original position of your number, look for it in the second, index column.

If your list is not made of numbers, the method still works and will be fastest, but you may need to define a function which can compare/order strings.

Of course, this needs the investment of the sorted() method, but if you keep reusing the same list for checking, it may be worth it.

The Android emulator is not starting, showing "invalid command-line parameter"

I had the same problem. I made it work with:

"C:\Program Files (x86)\Android\android-sdk\tools\emulator-arm.exe"  @foo

foo is the name of your virtual device.

Clear Cache in Android Application programmatically

If you are looking for delete cache of your own application then simply delete your cache directory and its all done !

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        deleteDir(dir);
    } catch (Exception e) { e.printStackTrace();}
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
        return dir.delete();
    } else if(dir!= null && dir.isFile()) {
        return dir.delete();
    } else {
        return false;
    }
}

Get the second largest number in a list in linear time

list_nums = [1, 2, 6, 6, 5]
minimum = float('-inf')
max, min = minimum, minimum
for num in list_nums:
    if num > max:
        max, min = num, max
    elif max > num > min:
        min = num
print(min if min != minimum else None)

Output

5

Create a dropdown component

If you want something with a dropdown (some list of values) and a user specified value that can be filled into the selected input as well. This custom dropdown in angular also has a filter dropdown list on key value entered. Please check this stackblitzlink -> https://stackblitz.com/edit/angular-l9guzo?embed=1&file=src/app/custom-textarea.component.ts

Django. Override save for model

Query the database for an existing record with the same PK. Compare the file sizes and checksums of the new and existing images to see if they're the same.

Python Write bytes to file

Write bytes and Create the file if not exists:

f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()

wb means open the file in write binary mode.

Is floating point math broken?

Floating point rounding error. From What Every Computer Scientist Should Know About Floating-Point Arithmetic:

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

What's the difference between lists and tuples?

If you went for a walk, you could note your coordinates at any instant in an (x,y) tuple.

If you wanted to record your journey, you could append your location every few seconds to a list.

But you couldn't do it the other way around.

How to Copy Contents of One Canvas to Another Canvas Locally

Actually you don't have to create an image at all. drawImage() will accept a Canvas as well as an Image object.

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);

Way faster than using an ImageData object or Image element.

Note that sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas.

Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element

How can I get query string values in JavaScript?

From the MDN:

function loadPageVar (sVar) {
  return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}

alert(loadPageVar("name"));

The type or namespace name 'System' could not be found

I had the same problem earlier when I tried to edit an open source project from the internet .

Solved it by just Cleaning the solution and rebuilding it .

Hope this helps.

How to exit from Python without traceback?

You are presumably encountering an exception and the program is exiting because of this (with a traceback). The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given).

Try something like this in your main routine:

import sys, traceback

def main():
    try:
        do main program stuff here
        ....
    except KeyboardInterrupt:
        print "Shutdown requested...exiting"
    except Exception:
        traceback.print_exc(file=sys.stdout)
    sys.exit(0)

if __name__ == "__main__":
    main()

Where do I find old versions of Android NDK?

Google has moved NDK releases to GitHub. Now, the Wiki page contains links to the current stable release, to available betas, and to selected older releases.

How do I bind onchange event of a TextBox using JQuery?

What Chad says, except its better to use .keyup in this case because with .keydown and .keypress the value of the input is still the older value i.e. the newest key pressed would not be reflected if .val() is called.

This should probably be a comment on Chad's answer but I dont have privileges to comment yet.

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

I stopped MySQL sudo service mysql stop and then started xammp sudo /opt/lampp/lampp start and it worked!

C/C++ include header file order

This is not subjective. Make sure your headers don't rely on being #included in specific order. You can be sure it doesn't matter what order you include STL or Boost headers.

Path.Combine absolute with relative path strings

Call Path.GetFullPath on the combined path http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx

> Path.GetFullPath(Path.Combine(@"C:\blah\",@"..\bling"))
C:\bling

(I agree Path.Combine ought to do this by itself)

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

I was getting the error A client error (403) occurred when calling the HeadObject operation: Forbidden for my aws cli copy command aws s3 cp s3://bucket/file file. I was using a IAM role which had full S3 access using an Inline Policy.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "*"
    }
  ]
}

If I give it the full S3 access from the Managed Policies instead, then the command works. I think this must be a bug from Amazon, because the policies in both cases were exactly the same.

multiple figure in latex with captions

Below is an example of multiple figures that I used recently in Latex. You need to call these packages

\usepackage{graphicx}
\usepackage{subfig})


\begin{figure}[H]%

    \centering

    \subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%

    \subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%

    \subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
    \hfill
    \subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%

    \subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%

    \caption{Multiple figures in latex.}%

    \label{fig:MFL}%

\end{figure}

Accessing items in an collections.OrderedDict by index

If you have pandas installed, you can convert the ordered dict to a pandas Series. This will allow random access to the dictionary elements.

>>> import collections
>>> import pandas as pd
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'

>>> s = pd.Series(d)

>>> s['bar']
spam
>>> s.iloc[1]
spam
>>> s.index[1]
bar

How to call any method asynchronously in c#

public partial class MainForm : Form
{
    Image img;
    private void button1_Click(object sender, EventArgs e)
    {
        LoadImageAsynchronously("http://media1.santabanta.com/full5/Indian%20%20Celebrities(F)/Jacqueline%20Fernandez/jacqueline-fernandez-18a.jpg");
    }

    private void LoadImageAsynchronously(string url)
    {
        /*
        This is a classic example of how make a synchronous code snippet work asynchronously.
        A class implements a method synchronously like the WebClient's DownloadData(…) function for example
            (1) First wrap the method call in an Anonymous delegate.
            (2) Use BeginInvoke(…) and send the wrapped anonymous delegate object as the last parameter along with a callback function name as the first parameter.
            (3) In the callback method retrieve the ar's AsyncState as a Type (typecast) of the anonymous delegate. Along with this object comes EndInvoke(…) as free Gift
            (4) Use EndInvoke(…) to retrieve the synchronous call’s return value in our case it will be the WebClient's DownloadData(…)’s return value.
        */
        try
        {
            Func<Image> load_image_Async = delegate()
            {
                WebClient wc = new WebClient();
                Bitmap bmpLocal = new Bitmap(new MemoryStream(wc.DownloadData(url)));
                wc.Dispose();
                return bmpLocal;
            };

            Action<IAsyncResult> load_Image_call_back = delegate(IAsyncResult ar)
            {
                Func<Image> ss = (Func<Image>)ar.AsyncState;
                Bitmap myBmp = (Bitmap)ss.EndInvoke(ar);

                if (img != null) img.Dispose();
                if (myBmp != null)
                    img = myBmp;
                Invalidate();
                //timer.Enabled = true;
            };
            //load_image_Async.BeginInvoke(callback_load_Image, load_image_Async);             
            load_image_Async.BeginInvoke(new AsyncCallback(load_Image_call_back), load_image_Async);             
        }
        catch (Exception ex)
        {

        }
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        if (img != null)
        {
            Graphics grfx = e.Graphics;
            grfx.DrawImage(img,new Point(0,0));
        }
    }

npm install -g less does not work: EACCES: permission denied

Using sudo is not recommended. It may give you permission issue later. While the above works, I am not a fan of changing folders owned by root to be writable for users, although it may only be an issue with multiple users. To work around that, you could use a group, with 'npm users' but that is also more administrative overhead. See here for the options to deal with permissions from the documentation: https://docs.npmjs.com/getting-started/fixing-npm-permissions

I would go for option 2:

To minimize the chance of permissions errors, you can configure npm to use a different directory. In this example, it will be a hidden directory on your home folder.

Make a directory for global installations:

 mkdir ~/.npm-global

Configure npm to use the new directory path:

 npm config set prefix '~/.npm-global'

Open or create a ~/.profile file and add this line:

 export PATH=~/.npm-global/bin:$PATH

Back on the command line, update your system variables:

 source ~/.profile

Test: Download a package globally without using sudo.

npm install -g jshint

If still show permission error run (mac os):

sudo chown -R $USER ~/.npm-global   

This works with the default ubuntu install of:

sudo apt-get install nodejs npm

I recommend nvm if you want more flexibility in managing versions: https://github.com/creationix/nvm

On MacOS use brew, it should work without sudo out of the box if you're on a recent npm version. Enjoy :)

EXCEL VBA Check if entry is empty or not 'space'

You can use the following code to check if a textbox object is null/empty

'Checks if the box is null

If Me.TextBox & "" <> "" Then

        'Enter Code here...

End if

Create a folder and sub folder in Excel VBA

This works like a charm in AutoCad VBA and I grabbed it from an excel forum. I don't know why you all make it so complicated?

FREQUENTLY ASKED QUESTIONS

Question: I'm not sure if a particular directory exists already. If it doesn't exist, I'd like to create it using VBA code. How can I do this?

Answer: You can test to see if a directory exists using the VBA code below:

(Quotes below are omitted to avoid confusion of programming code)


If Len(Dir("c:\TOTN\Excel\Examples", vbDirectory)) = 0 Then

   MkDir "c:\TOTN\Excel\Examples"

End If

http://www.techonthenet.com/excel/formulas/mkdir.php

Bootstrap center heading

Per your comments, to center all headings all you have to do is add text-align:center to all of them at the same time, like so:

CSS

    h1, h2, h3, h4, h5, h6 {
        text-align: center;
    }

preventDefault() on an <a> tag

Try something like:

$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
    event.preventDefault();
    $(this).next('div').slideToggle(200);
});

Here is the page about that in the jQuery documentation

How to change int into int64?

i := 23
i64 := int64(i)
fmt.Printf("%T %T", i, i64) // to print the data types of i and i64

Wordpress - Images not showing up in the Media Library

I had a same problem just now, with missing media library images for my blog. The images appeared to be right there in the media library and were definitely on the actual web server (checked via FTP).

As Allen Z advised I did "check Settings ? Media and make sure that Uploading Files folder is set to wp-content/uploads"

Mine were set to the default blank. I altered this to an absolute path http://www.example.com/wp-content/uploads

THIS DIDNT SOLVE THE PROBLEM when I refreshed the site in browser. However, I immediately changed the path back to blank (the default setting again) and everything came back! Woop

Everyone having this problem might want to try this before getting into the more technical fixes!

In C can a long printf statement be broken up into multiple lines?

If you want to break a string literal onto multiple lines, you can concatenate multiple strings together, one on each line, like so:

printf("name: %s\t"
"args: %s\t"
"value %d\t"
"arraysize %d\n", 
sp->name, 
sp->args, 
sp->value, 
sp->arraysize);

Send mail via Gmail with PowerShell V2's Send-MailMessage

I had massive problems with getting any of those scripts to work with sending mail in powershell. Turned out you need to create an app-password for your gmail-account to authenticate in the script. Now it works flawlessly!

JavaScript post request like a form submit

If you have Prototype installed, you can tighten up the code to generate and submit the hidden form like this:

 var form = new Element('form',
                        {method: 'post', action: 'http://example.com/'});
 form.insert(new Element('input',
                         {name: 'q', value: 'a', type: 'hidden'}));
 $(document.body).insert(form);
 form.submit();

How to align input forms in HTML

css I used to solve this problem, similar to Gjaa but styled better

p
{
    text-align:center;
        }
.styleform label
{
    float:left;
    width: 40%;
    text-align:right;
    }
.styleform input
{
    float:left;
    width: 30%;
    }

Here is my HTML, used specifically for a simple registration form with no php code

<form id="registration">
    <h1>Register</h1>
    <div class="styleform">
    <fieldset id="inputs">
        <p><label>Name:</label> 
          <input id="name" type="text" placeholder="Name" autofocus required>
        </p>
        <p><label>Email:</label>   
          <input id="email" type="text" placeholder="Email Address" required>
        </p>
        <p><label>Username:</label>
          <input id="username" type="text" placeholder="Username" autofocus required>
        </p>
        <p>   
          <label>Password:</label>
          <input id="password" type="password" placeholder="Password" required>
        </p>
    </fieldset>
    <fieldset id="actions">

    </fieldset>
    </div>
    <p>
          <input type="submit" id="submit" value="Register">
          </p>

It's very simple, and I'm just beginning, but it worked quite nicely

if var == False

I think what you are looking for is the 'not' operator?

if not var

Reference page: http://www.tutorialspoint.com/python/logical_operators_example.htm

warning: assignment makes integer from pointer without a cast

What Jeremiah said, plus the compiler issues the warning because the production:

*src ="anotherstring";

says: take the address of "anotherstring" -- "anotherstring" IS a char pointer -- and store that pointer indirect through src (*src = ... ) into the first char of the string "abcdef..." The warning might be baffling because there is nowhere in your code any mention of any integer: the warning seems nonsensical. But, out of sight behind the curtain, is the rule that "int" and "char" are synonymous in terms of storage: both occupy the same number of bits. The compiler doesn't differentiate when it issues the warning that you are storing into an integer. Which, BTW, is perfectly OK and legal but probably not exactly what you want in this code.

-- pete

Quick way to create a list of values in C#?

If you're looking to reduce clutter, consider

var lst = new List<string> { "foo", "bar" };

This uses two features of C# 3.0: type inference (the var keyword) and the collection initializer for lists.

Alternatively, if you can make do with an array, this is even shorter (by a small amount):

var arr = new [] { "foo", "bar" };

Moment.js - tomorrow, today and yesterday

You can use this:


const today     = moment();

const tomorrow  = moment().add(1, 'days');

const yesterday = moment().subtract(1, 'days');

Load image from resources

    this.toolStrip1 = new System.Windows.Forms.ToolStrip();
    this.toolStrip1.Location = new System.Drawing.Point(0, 0);
    this.toolStrip1.Name = "toolStrip1";
    this.toolStrip1.Size = new System.Drawing.Size(444, 25);
    this.toolStrip1.TabIndex = 0;
    this.toolStrip1.Text = "toolStrip1";
    object O = global::WindowsFormsApplication1.Properties.Resources.ResourceManager.GetObject("best_robust_ghost");

    ToolStripButton btn = new ToolStripButton("m1");
    btn.DisplayStyle = ToolStripItemDisplayStyle.Image;
    btn.Image = (Image)O;
    this.toolStrip1.Items.Add(btn);

    this.Controls.Add(this.toolStrip1);

Disable cross domain web security in Firefox

I have not been able to find a Firefox option equivalent of --disable-web-security or an addon that does that for me. I really needed it for some testing scenarios where modifying the web server was not possible. What did help was to use Fiddler to auto-modify web responses so that they have the correct headers and CORS is no longer an issue.

The steps are:

  1. Open fiddler.

  2. If on https go to menu Tools -> Options -> Https and tick the Capture & Decrypt https options

  3. Go to menu Rules -> Customize rules. Modify the OnBeforeResponseFunction so that it looks like the following, then save:

     static function OnBeforeResponse(oSession: Session) {
        //....
        oSession.oResponse.headers.Remove("Access-Control-Allow-Origin");
        oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
        //...
     }
    

    This will make every web response to have the Access-Control-Allow-Origin: * header.

  4. This still won't work as the OPTIONS preflight will pass through and cause the request to block before our above rule gets the chance to modify the headers. So to fix this, in the fiddler main window, on the right hand side there's an AutoResponder tab. Add a new rule and response: METHOD:OPTIONS https://yoursite.com/ with auto response: *CORSPreflightAllow and tick the boxes: "Enable Rules" and "Unmatched requests passthrough".

See picture below for reference:

enter image description here

Style jQuery autocomplete in a Bootstrap input field

Try this (demo):

.ui-autocomplete {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 1000;
  display: none;
  float: left;
  min-width: 160px;
  padding: 5px 0;
  margin: 2px 0 0;
  list-style: none;
  font-size: 14px;
  text-align: left;
  background-color: #ffffff;
  border: 1px solid #cccccc;
  border: 1px solid rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  background-clip: padding-box;
}

.ui-autocomplete > li > div {
  display: block;
  padding: 3px 20px;
  clear: both;
  font-weight: normal;
  line-height: 1.42857143;
  color: #333333;
  white-space: nowrap;
}

.ui-state-hover,
.ui-state-active,
.ui-state-focus {
  text-decoration: none;
  color: #262626;
  background-color: #f5f5f5;
  cursor: pointer;
}

.ui-helper-hidden-accessible {
  border: 0;
  clip: rect(0 0 0 0);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
}

How to get the id of the element clicked using jQuery

I wanted to share how you can use this to change a attribute of the button, because it took me some time to figure it out...

For example in order to change it's background to yellow:

$("#"+String(this.id)).css("background-color","yellow");

Google Maps API v3 marker with label

the above solutions wont work on ipad-2

recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers this blog and now my map search is working smoothly on ipad-2 :)

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

ExpressJS How to structure an application?

I like to use a global "app", rather than exporting a function etc

What can be the reasons of connection refused errors?

If you try to open a TCP connection to another host and see the error "Connection refused," it means that

  1. You sent a TCP SYN packet to the other host.
  2. Then you received a TCP RST packet in reply.

RST is a bit on the TCP packet which indicates that the connection should be reset. Usually it means that the other host has received your connection attempt and is actively refusing your TCP connection, but sometimes an intervening firewall may block your TCP SYN packet and send a TCP RST back to you.

See https://tools.ietf.org/html/rfc793 page 69:

SYN-RECEIVED STATE

If the RST bit is set

If this connection was initiated with a passive OPEN (i.e., came from the LISTEN state), then return this connection to LISTEN state and return. The user need not be informed. If this connection was initiated with an active OPEN (i.e., came from SYN-SENT state) then the connection was refused, signal the user "connection refused". In either case, all segments on the retransmission queue should be removed. And in the active OPEN case, enter the CLOSED state and delete the TCB, and return.

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

I had a similar problem with é char... I think the comment "it's possible that the text you're feeding it isn't UTF-8" is probably close to the mark here. I have a feeling the default collation in my instance was something else until I realized and changed to utf8... problem is the data was already there, so not sure if it converted the data or not when i changed it, displays fine in mysql workbench. End result is that php will not json encode the data, just returns false. Doesn't matter what browser you use as its the server causing my issue, php will not parse the data to utf8 if this char is present. Like i say not sure if it is due to converting the schema to utf8 after data was present or just a php bug. In this case use json_encode(utf8_encode($string));

Method has the same erasure as another method in type

Define a single Method without type like void add(Set ii){}

You can mention the type while calling the method based on your choice. It will work for any type of set.

How can I do a line break (line continuation) in Python?

From PEP 8 -- Style Guide for Python Code:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:

with open('/path/to/some/file/you/want/to/read') as file_1, \
        open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

Another such case is with assert statements.

Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. Some examples:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

PEP8 now recommends the opposite convention (for breaking at binary operations) used by mathematicians and their publishers to improve readability.

Donald Knuth's style of breaking before a binary operator aligns operators vertically, thus reducing the eye's workload when determining which items are added and subtracted.

From PEP8: Should a line break before or after a binary operator?:

Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations"[3].

Following the tradition from mathematics usually results in more readable code:

# Yes: easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.

[3]: Donald Knuth's The TeXBook, pages 195 and 196

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

[UPDATED privacy keys list to iOS 13 - see below]

There is a list of all Cocoa Keys that you can specify in your Info.plist file:

https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html

(Xcode: Target -> Info -> Custom iOS Target Properties)

iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).

Privacy keys with example description: cheatsheet

Source

Alternatively, you can open Info.plist as source code: source code

Source

And add privacy keys like this:

<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>

List of all privacy keys: [UPDATED to iOS 13]

NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription

Update 2019:

In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.

I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo to ${PRODUCT_NAME} need access to the camera to update your avatar even though the app context was obvious (user tapped on the avatar).

It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.

Mockito matcher and array of primitives

You can always create a custom Matcher using argThat

Mockito.verify(yourMockHere).methodCallToBeVerifiedOnYourMockHere(ArgumentMatchers.argThat(new ArgumentMatcher<Object>() {
    @Override
    public boolean matches(Object argument) {
        YourTypeHere[] yourArray = (YourTypeHere[]) argument;
        // Do whatever you like, here is an example:
        if (!yourArray[0].getStringValue().equals("first_arr_val")) {
            return false;
        }
        return true;
    }
}));

How to set environment variable or system property in spring tests?

The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource annotation.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
    ...    
}

See @TestPropertySource in the Spring docs and Javadocs.

using jquery $.ajax to call a PHP function

Use $.ajax to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:

$.ajax({ url: '/my/site',
         data: {action: 'test'},
         type: 'post',
         success: function(output) {
                      alert(output);
                  }
});

On the server side, the action POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'test' : test();break;
        case 'blah' : blah();break;
        // ...etc...
    }
}

I believe that's a simple incarnation of the Command pattern.

How to do a logical OR operation for integer comparison in shell scripting?

If you are using the bash exit code status $? as variable, it's better to do this:

if [ $? -eq 4 -o $? -eq 8 ] ; then  
   echo "..."
fi

Because if you do:

if [ $? -eq 4 ] || [ $? -eq 8 ] ; then  

The left part of the OR alters the $? variable, so the right part of the OR doesn't have the original $? value.

java howto ArrayList push, pop, shift, and unshift

I was facing with this problem some time ago and I found java.util.LinkedList is best for my case. It has several methods, with different namings, but they're doing what is needed:

push()    -> LinkedList.addLast(); // Or just LinkedList.add();
pop()     -> LinkedList.pollLast();
shift()   -> LinkedList.pollFirst();
unshift() -> LinkedList.addFirst();

Android: How to change CheckBox size?

I found a way to do it without creating your own images. In other words, the system image is being scaled. I don't pretend that the solution is perfect; if anyone knows a way to shorten some of the steps, I'll be happy to find out how.

First, I put the following in the main activity class of the project (WonActivity) . This was taken directly from Stack Overflow -- thank you guys!

/** get the default drawable for the check box */
Drawable getDefaultCheckBoxDrawable()
{
  int resID = 0;

  if (Build.VERSION.SDK_INT <= 10)
  {
    // pre-Honeycomb has a different way of setting the CheckBox button drawable
    resID = Resources.getSystem().getIdentifier("btn_check", "drawable", "android");
  }
  else
  {
    // starting with Honeycomb, retrieve the theme-based indicator as CheckBox button drawable
    TypedValue value = new TypedValue();
    getApplicationContext().getTheme().resolveAttribute(android.R.attr.listChoiceIndicatorMultiple, value, true);
    resID = value.resourceId;
  }

  return getResources().getDrawable(resID);
}

Second, I created a class to "scale a drawable". Please notice that it is completely different from the standard ScaleDrawable.

import android.graphics.drawable.*;

/** The drawable that scales the contained drawable */

public class ScalingDrawable extends LayerDrawable
{
  /** X scale */
  float scaleX;

  /** Y scale */
  float scaleY;

  ScalingDrawable(Drawable d, float scaleX, float scaleY)
  {
    super(new Drawable[] { d });
    setScale(scaleX, scaleY);
  }

  ScalingDrawable(Drawable d, float scale)
  {
    this(d, scale, scale);
  }

  /** set the scales */
  void setScale(float scaleX, float scaleY)
  {
    this.scaleX = scaleX;
    this.scaleY = scaleY;
  }

  /** set the scale -- proportional scaling */
  void setScale(float scale)
  {
    setScale(scale, scale);
  }

  // The following is what I wrote this for!

  @Override
  public int getIntrinsicWidth()
  {
    return (int)(super.getIntrinsicWidth() * scaleX);
  }

  @Override
  public int getIntrinsicHeight()
  {
    return (int)(super.getIntrinsicHeight() * scaleY);
  }
}

Finally, I defined a checkbox class.

import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.widget.*;

/** A check box that resizes itself */

public class WonCheckBox extends CheckBox
{
  /** the check image */
  private ScalingDrawable checkImg;

  /** original height of the check-box image */
  private int origHeight;

  /** original padding-left */
  private int origPadLeft;

  /** height set by the user directly */
  private float height;

  WonCheckBox()
  {
    super(WonActivity.W.getApplicationContext());
    setBackgroundColor(Color.TRANSPARENT);

    // get the original drawable and get its height
    Drawable origImg = WonActivity.W.getDefaultCheckBoxDrawable();
    origHeight = height = origImg.getIntrinsicHeight();
    origPadLeft = getPaddingLeft();

    // I tried origImg.mutate(), but that fails on Android 2.1 (NullPointerException)
    checkImg = new ScalingDrawable(origImg, 1);
    setButtonDrawable(checkImg);
  }

  /** set checkbox height in pixels directly */
  public void setHeight(int height)
  {
    this.height = height;
    float scale = (float)height / origHeight;
    checkImg.setScale(scale);

    // Make sure the text is not overlapping with the image.
    // This is unnecessary on Android 4.2.2, but very important on previous versions.
    setPadding((int)(scale * origPadLeft), 0, 0, 0);

    // call the checkbox's internal setHeight()
    //   (may be unnecessary in your case)
    super.setHeight(height);
  }
}

That's it. If you put a WonCheckBox in your view and apply setHeight(), the check-box image will be of the right size.

DropDownList in MVC 4 with Razor

_x000D_
_x000D_
List<tblstatu> status = new List<tblstatu>();_x000D_
            status = psobj.getstatus();_x000D_
            model.statuslist = status;_x000D_
            model.statusid = status.Select(x => new SelectListItem_x000D_
            {_x000D_
                Value = x.StatusId.ToString(),_x000D_
                Text = x.StatusName_x000D_
            });_x000D_
_x000D_
_x000D_
  @Html.DropDownListFor(m => m.status_id, Model.statusid, "Select", new { @class = "form-control input-xlarge required", @type = "text", @autocomplete = "off" })
_x000D_
_x000D_
_x000D_

How can I switch themes in Visual Studio 2012

Slightly off topic, but for those of you that want to modify the built-in colors of the Dark/Light themes you can use this little tool I wrote for Visual Studio 2012.

More info here:

Modify Visual Studio 2012 Dark (and Light) Themes

Source Code

How do I compare strings in Java?

In Java, when the == operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.

The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

The == operator checks if the two strings are exactly the same object.

The .equals() method check if the two strings have the same value.

How to POST form data with Spring RestTemplate?

How to POST mixed data: File, String[], String in one request.

You can use only what you need.

private String doPOST(File file, String[] array, String name) {
    RestTemplate restTemplate = new RestTemplate(true);

    //add file
    LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("file", new FileSystemResource(file));

    //add array
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
    for (String item : array) {
        builder.queryParam("array", item);
    }

    //add some String
    builder.queryParam("name", name);

    //another staff
    String result = "";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
            new HttpEntity<>(params, headers);

    ResponseEntity<String> responseEntity = restTemplate.exchange(
            builder.build().encode().toUri(),
            HttpMethod.POST,
            requestEntity,
            String.class);

    HttpStatus statusCode = responseEntity.getStatusCode();
    if (statusCode == HttpStatus.ACCEPTED) {
        result = responseEntity.getBody();
    }
    return result;
}

The POST request will have File in its Body and next structure:

POST https://my_url?array=your_value1&array=your_value2&name=bob 

How can I extract a predetermined range of lines from a text file on Unix?

I wrote a Haskell program called splitter that does exactly this: have a read through my release blog post.

You can use the program as follows:

$ cat somefile | splitter 16224-16482

And that is all that there is to it. You will need Haskell to install it. Just:

$ cabal install splitter

And you are done. I hope that you find this program useful.

How can I append a query parameter to an existing URL?

This can be done by using the java.net.URI class to construct a new instance using the parts from an existing one, this should ensure it conforms to URI syntax.

The query part will either be null or an existing string, so you can decide to append another parameter with & or start a new query.

public class StackOverflow26177749 {

    public static URI appendUri(String uri, String appendQuery) throws URISyntaxException {
        URI oldUri = new URI(uri);

        String newQuery = oldUri.getQuery();
        if (newQuery == null) {
            newQuery = appendQuery;
        } else {
            newQuery += "&" + appendQuery;  
        }

        return new URI(oldUri.getScheme(), oldUri.getAuthority(),
                oldUri.getPath(), newQuery, oldUri.getFragment());
    }

    public static void main(String[] args) throws Exception {
        System.out.println(appendUri("http://example.com", "name=John"));
        System.out.println(appendUri("http://example.com#fragment", "name=John"));
        System.out.println(appendUri("http://[email protected]", "name=John"));
        System.out.println(appendUri("http://[email protected]#fragment", "name=John"));
    }
}

Shorter alternative

public static URI appendUri(String uri, String appendQuery) throws URISyntaxException {
    URI oldUri = new URI(uri);
    return new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(),
            oldUri.getQuery() == null ? appendQuery : oldUri.getQuery() + "&" + appendQuery, oldUri.getFragment());
}

Output

http://example.com?name=John
http://example.com?name=John#fragment
http://[email protected]&name=John
http://[email protected]&name=John#fragment

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

For anyone looking for a UI option using IIS Manager.

  1. Open the Website in IIS Manager
  2. Go To Request Filtering and open the Request Filtering Window.
  3. Go to Verbs Tab and Add HTTP Verbs to "Allow Verb..." or "Deny Verb...". This allow to add the HTTP Verbs in the "Deny Verb.." Collection.

Request Filtering Window in IIS Manager Request Filtering Window in IIS Manager

Add Verb... or Deny Verb... enter image description here

Base64 decode snippet in C++

I use this:

class BinaryVector {
public:
    std::vector<char> bytes;

    uint64_t bit_count = 0;

public:
    /* Add a bit to the end */
    void push_back(bool bit);

    /* Return false if character is unrecognized */
    bool pushBase64Char(char b64_c);
};

void BinaryVector::push_back(bool bit)
{
    if (!bit_count || bit_count % 8 == 0) {
        bytes.push_back(bit << 7);
    }
    else {
        uint8_t next_bit = 8 - (bit_count % 8) - 1;
        bytes[bit_count / 8] |= bit << next_bit;
    }
    bit_count++;
}

/* Converts one Base64 character to 6 bits */
bool BinaryVector::pushBase64Char(char c)
{
    uint8_t d;

    // A to Z
    if (c > 0x40 && c < 0x5b) {
        d = c - 65;  // Base64 A is 0
    }
    // a to z
    else if (c > 0x60 && c < 0x7b) {
        d = c - 97 + 26;  // Base64 a is 26
    }
    // 0 to 9
    else if (c > 0x2F && c < 0x3a) {
        d = c - 48 + 52;  // Base64 0 is 52
    }
    else if (c == '+') {
        d = 0b111110;
    }
    else if (c == '/') {
        d = 0b111111;
    }
    else if (c == '=') {
        d = 0;
    }
    else {
        return false;
    }

    push_back(d & 0b100000);
    push_back(d & 0b010000);
    push_back(d & 0b001000);
    push_back(d & 0b000100);
    push_back(d & 0b000010);
    push_back(d & 0b000001);

    return true;
}

bool loadBase64(std::vector<char>& b64_bin, BinaryVector& vec)
{
    for (char& c : b64_bin) {
        if (!vec.pushBase64Char(c)) {
            return false;
        }
    }
    return true;
}

Use vec.bytes to access converted data.

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

I think this could be useful for you.

_x000D_
_x000D_
const myObject = {_x000D_
   "a":"a",_x000D_
   "b":{_x000D_
      "c":"c",_x000D_
      "d":{_x000D_
         "e":"e",_x000D_
         "f":{_x000D_
            "g":"g",_x000D_
            "h":{_x000D_
               "i":"i"_x000D_
            }_x000D_
         }_x000D_
      }_x000D_
   }_x000D_
};_x000D_
_x000D_
console.log(JSON.stringify(myObject, null, '\t'));
_x000D_
_x000D_
_x000D_

As mentioned in this answer:

JSON.stringify's third parameter defines white-space insertion for pretty-printing. It can be a string or a number (number of spaces).

moment.js - UTC gives wrong date

Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.

The correct way to parse an input moment as UTC in the format you provided would be like this:

moment.utc('07-18-2013', 'MM-DD-YYYY')

Refer to this documentation.

If you want to then format it differently for output, you would do this:

moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')

You do not need to call toString explicitly.

Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.

Serializing list to JSON

If using Python 2.5, you may need to import simplejson:

try:
    import json
except ImportError:
    import simplejson as json

How to change Java version used by TOMCAT?

test open the termenal or cmd. go to the [tomcat-home]\bin directory. ex: c:\tomcat8\bin write the following command: Tomcat8W //ES//Tomcat8 will open dialog, select the java tap(top tap). change the Java virtual Machine value.

What is the difference between MySQL, MySQLi and PDO?

Specifically, the MySQLi extension provides the following extremely useful benefits over the old MySQL extension..

OOP Interface (in addition to procedural) Prepared Statement Support Transaction + Stored Procedure Support Nicer Syntax Speed Improvements Enhanced Debugging

PDO Extension

PHP Data Objects extension is a Database Abstraction Layer. Specifically, this is not a MySQL interface, as it provides drivers for many database engines (of course including MYSQL).

PDO aims to provide a consistent API that means when a database engine is changed, the code changes to reflect this should be minimal. When using PDO, your code will normally "just work" across many database engines, simply by changing the driver you're using.

In addition to being cross-database compatible, PDO also supports prepared statements, stored procedures and more, whilst using the MySQL Driver.

How to get CSS to select ID that begins with a string (not in Javascript)?

I'd do it like this:

[id^="product"] {
  ...
}

Ideally, use a class. This is what classes are for:

<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>

And now the selector becomes:

.product {
  ...
}

Check existence of input argument in a Bash shell script

Another way to detect if arguments were passed to the script:

((!$#)) && echo No arguments supplied!

Note that (( expr )) causes the expression to be evaluated as per rules of Shell Arithmetic.

In order to exit in the absence of any arguments, one can say:

((!$#)) && echo No arguments supplied! && exit 1

Another (analogous) way to say the above would be:

let $# || echo No arguments supplied

let $# || { echo No arguments supplied; exit 1; }  # Exit if no arguments!

help let says:

let: let arg [arg ...]

  Evaluate arithmetic expressions.

  ...

  Exit Status:
  If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise.

Resetting remote to a certain commit

Let's assume that your branch is called master both locally and remotely, and that your remote is called origin you could do:

git reflog to get all the commit history, your commit hash has format like this: e34e1ff

git reset --hard <commit-hash>

git push -f origin master

What does the 'static' keyword do in a class?

Static Variables Can only be accessed only in static methods, so when we declare the static variables those getter and setter methods will be static methods

static methods is a class level we can access using class name

The following is example for Static Variables Getters And Setters:

public class Static 
{

    private static String owner;
    private static int rent;
    private String car;
    public String getCar() {
        return car;
    }
    public void setCar(String car) {
        this.car = car;
    }
    public static int getRent() {
        return rent;
    }
    public static void setRent(int rent) {
        Static.rent = rent;
    }
    public static String getOwner() {
        return owner;
    }

    public static void setOwner(String owner) {
        Static.owner = owner;
    }

}

How can I disable a button in a jQuery dialog from a function?

Just for the record, this post helped me to solve my problem. In short words, you have to set the disabled attribute to disabled, not to false:

_send_button.attr('disabled','disabled');

This is how all the code looks, I also added some styles to make it look disabled:

var _send_button = $('.ui-dialog-buttonpane button:contains(Send)');
var original_text = _send_button.text();
_send_button.text('Please wait...');
_send_button.addClass('ui-state-disabled');
_send_button.attr('disabled','disabled');
_send_button.fadeTo(500,0.2);

Lodash remove duplicates from array

Simply use _.uniqBy(). It creates duplicate-free version of an array.

This is a new way and available from 4.0.0 version.

_.uniqBy(data, 'id');

or

_.uniqBy(data, obj => obj.id);

How can I make git accept a self signed certificate?

It’s not a good practice to set http.sslVerify false. Instead we can use SSL certificate.

So, build agent will use https with SSL certificate and PAT for authentication. enter image description here

enter image description here

enter image description here

Copy the content of cer file including –begin—and –end--.

git bash on build agent => git config –global http.sslcainfo “C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt” Go to this file and append the .cer content.

Thus, build agent can access the SSL certificate

replace \n and \r\n with <br /> in java

Since my account is new I can't up-vote Nino van Hooff's answer. If your strings are coming from a Windows based source such as an aspx based server, this solution does work:

rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "<br />");

Seems to be a weird character set issue as the double back-slashes are being interpreted as single slash escape characters. Hence the need for the quadruple slashes above.

Again, under most circumstances "(\\r\\n|\\n)" should work, but if your strings are coming from a Windows based source try the above.

Just an FYI tried everything to correct the issue I was having replacing those line endings. Thought at first was failed conversion from Windows-1252 to UTF-8. But that didn't working either. This solution is what finally did the trick. :)

Leading zeros for Int in Swift

Assuming you want a field length of 2 with leading zeros you'd do this:

import Foundation

for myInt in 1 ... 3 {
    print(String(format: "%02d", myInt))
}

output:

01
02
03

This requires import Foundation so technically it is not a part of the Swift language but a capability provided by the Foundation framework. Note that both import UIKit and import Cocoa include Foundation so it isn't necessary to import it again if you've already imported Cocoa or UIKit.


The format string can specify the format of multiple items. For instance, if you are trying to format 3 hours, 15 minutes and 7 seconds into 03:15:07 you could do it like this:

let hours = 3
let minutes = 15
let seconds = 7
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))

output:

03:15:07

Any tools to generate an XSD schema from an XML instance document?

If all you want is XSD, LiquidXML has a free version that does XSDs, and its got a GUI to it so you can tweak the XSD if you like. Anyways nowadays I write my own XSDs by hand, but its all thanks to this app.

http://www.liquid-technologies.com/

Can anyone explain me StandardScaler?

This is useful when you want to compare data that correspond to different units. In that case, you want to remove the units. To do that in a consistent way of all the data, you transform the data in a way that the variance is unitary and that the mean of the series is 0.

Express-js wildcard routing to cover everything under and including a path

For those who are learning node/express (just like me): do not use wildcard routing if possible!

I also wanted to implement the routing for GET /users/:id/whatever using wildcard routing. This is how I got here.

More info: https://blog.praveen.science/wildcard-routing-is-an-anti-pattern/

How do I auto-submit an upload form when a file is selected?

Using jQuery:

_x000D_
_x000D_
$('#file').change(function() {_x000D_
  $('#target').submit();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form id="target" action="destination.html">_x000D_
  <input type="file" id="file" value="Go" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Form submit with AJAX passing form data to PHP without page refresh

The form is submitting after the ajax request.

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'post',
            url: 'post.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form>
      <input name="time" value="00:00:00.00"><br>
      <input name="date" value="0000-00-00"><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

What's the best visual merge tool for Git?

I've tried a lot of the tools mentioned here and none of them have quite been what I'm looking for.

Personally, I've found Atom to be a great tool for visualizing differences and conflict resolution/merging.

As for merging, there aren't three views but it's all combined into one with colored highlighting for each version. You can edit the code directly or there are buttons to use whichever version of that snippet you want.

I don't even use it as an editor or IDE anymore, just for working with git. Clean UI and very straight-forward, plus it's highly customizable.

  • You can start it from the command line and pass in a single file you want to open to, or add your project folder (git repo).

    • I would also recommend project-manager as a very convenient way to navigate between projects without filling up your tree view.
  • The only problem I've had is refreshing -- when working with large repositories atom can be slow to update changes you make outside of it. I just always close it when I'm finished, and then reopen when I want to view my changes/commit again. You can also reload the window with ctrl+shift+f5, which only takes a second.

And it's free of course.

Sending simple message body + file attachment using Linux Mailx

The best way is to use mpack!

mpack -s "Subject" -d "./body.txt" "././image.png" mailadress

mpack - subject - body - attachment - mailadress

How to force C# .net app to run only one instance in Windows?

I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded

using System.Threading;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
   bool createdNew = true;
   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
   {
      if (createdNew)
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
      else
      {
         Process current = Process.GetCurrentProcess();
         foreach (Process process in Process.GetProcessesByName(current.ProcessName))
         {
            if (process.Id != current.Id)
            {
               SetForegroundWindow(process.MainWindowHandle);
               break;
            }
         }
      }
   }
}

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

Add

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

What are .tpl files? PHP, web design

.tpl shows there is a smarty! Smarty is a template language to split out PHP code from HTML code. Which gives us to the ability to do design stuff on a page which has not included PHP code.

get the value of "onclick" with jQuery?

i have never done this, but it would be done like this:

var script = $('#google').attr("onclick")

ESLint - "window" is not defined. How to allow global variables in package.json

I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:

Make sure ESLint is not run with the --no-inline-config flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):

/* eslint-env browser */

This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.

There are plenty of environments, and you can declare more than one at the same time, for example, in-line:

/* eslint-env browser, node */

If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.

From their docs:

An environment defines global variables that are predefined. The available environments are:

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node and Browser.

[...]

Besides environments, you can make it ignore anything you want. If it warns you about using console.log() but you don't want to be warned about it, just inline:

/* eslint-disable no-console */

You can see the list of all rules, including recommended rules to have for best coding practices.

Using Mockito's generic "any()" method

This should work

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;

verify(bar).DoStuff(any(Foo[].class));

Cannot assign requested address using ServerSocket.socketBind

The error says Cannot assign requested address. This means that you need to use the correct address for one of your network interfaces or 0.0.0.0 to accept connections from all interfaces.

The other solutions about ports only work after sometimes-failing black magic (like working after some computer restarts but not others) because the port is completely irrelevant.

Javascript string/integer comparisons

use parseInt and compare like below:

javascript:alert(parseInt("2")>parseInt("10"))

JavaScript/jQuery - How to check if a string contain specific words

If you are looking for exact words and don't want it to match things like "nightmare" (which is probably what you need), you can use a regex:

/\bare\b/gi

\b = word boundary
g = global
i = case insensitive (if needed)

If you just want to find the characters "are", then use indexOf.

If you want to match arbitrary words, you have to programatically construct a RegExp (regular expression) object itself based on the word string and use test.

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

If your main project using some library projects and have reference to them, you can cause this problem if your project reference to a assembly dll file instead to library project when you change something in your library project (ex: rename a class).

You can check all references to your main project by view in Object Browser window (menu View->Object Browser). A reference to a dll file always has a version number. Ex: TestLib [1.0.0.0]

Solution: delete the current reference of your main project to the library project and add reference to that library project again.

Select row on click react-table

I am not familiar with, react-table, so I do not know it has direct support for selecting and deselecting (it would be nice if it had).

If it does not, with the piece of code you already have you can install the onCLick handler. Now instead of trying to attach style directly to row, you can modify state, by for instance adding selected: true to row data. That would trigger rerender. Now you only have to override how are rows with selected === true rendered. Something along lines of:

// Any Tr element will be green if its (row.age > 20) 
<ReactTable
  getTrProps={(state, rowInfo, column) => {
    return {
      style: {
        background: rowInfo.row.selected ? 'green' : 'red'
      }
    }
  }}
/>

How to get the current location latitude and longitude in android

You can use following class as service class to run your application in background

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

    private GPSTracker gpsTracker;
    private Handler handler= new Handler();
    private Timer timer = new Timer();
    private Distance pastDistance = new Distance();
     private Distance currentDistance = new Distance();
    public static double DISTANCE;
    boolean flag = true ;
    private double totalDistance ;
    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {

        super.onStart(intent, startId);
        gpsTracker = new GPSTracker(HomeFragment.HOMECONTEXT);
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        if(flag){
                            pastDistance.setLatitude(gpsTracker.getLocation().getLatitude());
                            pastDistance.setLongitude(gpsTracker.getLocation().getLongitude());
                            flag = false;
                        }else{
                            currentDistance.setLatitude(gpsTracker.getLocation().getLatitude());
                            currentDistance.setLongitude(gpsTracker.getLocation().getLongitude());
                            flag = comapre_LatitudeLongitude();
                        }
                        Toast.makeText(HomeFragment.HOMECONTEXT, "latitude:"+gpsTracker.getLocation().getLatitude(), 4000).show();

                    }
                });


            }
        };

        timer.schedule(timerTask,0, 5000);

    }

    private double distance(double lat1, double lon1, double lat2, double lon2) {
          double theta = lon1 - lon2;
          double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
          dist = Math.acos(dist);
          dist = rad2deg(dist);
          dist = dist * 60 * 1.1515;
           return (dist);
        }

       private double deg2rad(double deg) {
          return (deg * Math.PI / 180.0);
        }
       private double rad2deg(double rad) {
          return (rad * 180.0 / Math.PI);
   }


    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }



    @Override
    public void onDestroy() {

        super.onDestroy();
        System.out.println("--------------------------------onDestroy -stop service ");
        timer.cancel();
        DISTANCE = totalDistance ;
    }
    public boolean comapre_LatitudeLongitude(){

        if(pastDistance.getLatitude() == currentDistance.getLatitude() && pastDistance.getLongitude() == currentDistance.getLongitude()){
            return false;
        }else{

            final double distance = distance(pastDistance.getLatitude(),pastDistance.getLongitude(),currentDistance.getLatitude(),currentDistance.getLongitude());
            System.out.println("Distance in mile :"+distance);
            handler.post(new Runnable() {

                @Override
                public void run() {
                    float kilometer=1.609344f;

                    totalDistance = totalDistance +  distance * kilometer;
                    DISTANCE = totalDistance;
                    //Toast.makeText(HomeFragment.HOMECONTEXT, "distance in km:"+DISTANCE, 4000).show();

                }
            });

            return true;
        }

    }

}

Add One another class to get location

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class GPSTracker implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location = null; 
double latitude; 
double longitude; 

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

protected LocationManager locationManager;
private Location m_Location;
 public GPSTracker(Context context) {
    this.mContext = context;
    m_Location = getLocation();
    System.out.println("location Latitude:"+m_Location.getLatitude());
    System.out.println("location Longitude:"+m_Location.getLongitude());
    System.out.println("getLocation():"+getLocation());
    }

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(Context.LOCATION_SERVICE);

        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } 
        else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    return latitude;
}

public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    return longitude;
}

public boolean canGetLocation() {
    return this.canGetLocation;
}

@Override
public void onLocationChanged(Location arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}


}

// --------------Distance.java

 public class Distance  {
    private double latitude ;
    private double longitude;
        public double getLatitude() {
            return latitude;
        }
        public void setLatitude(double latitude) {
            this.latitude = latitude;
        }
        public double getLongitude() {
            return longitude;
        }
        public void setLongitude(double longitude) {
            this.longitude = longitude;
        }



}

How to get multiple select box values using jQuery?

Just use this

$('#multipleSelect').change(function() {
    var selectedValues = $(this).val();  
});

Change link color of the current page with CSS

So for example if you are trying to change the text of the anchor on the current page that you are on only using CSS, then here is a simple solution.

I want to change the anchor text colour on my software page to light blue:

<div class="navbar">
    <ul>
       <a href="../index.html"><li>Home</li></a>
       <a href="usefulsites.html"><li>Useful Sites</li></a>
       <a href="software.html"><li class="currentpage">Software</li></a>
       <a href="workbench.html"><li>The Workbench</li></a>
       <a href="contact.php"><li>Contact</a></li></a>
    </ul>
</div>

And before anyone says that I got the <li> tags and the <a> tags mixed up, this is what makes it work as you are applying the value to the text itself only when you are on that page. Unfortunately, if you are using PHP to input header tags, then this will not work for obvious reasons. Then I put this in my style.css, with all my pages using the same style sheet:

.currentpage {
        color: lightblue;
}

How to initialize a struct in accordance with C programming language standards

a = (MYTYPE){ true, 15, 0.123 };

would do fine in C99

SimpleXml to string

You can use casting:

<?php

$string = "<element><child>Hello World</child></element>";
$xml = new SimpleXMLElement($string);

$text = (string)$xml->child;

$text will be 'Hello World'

Why can't I reference my class library?

I faced this problem, and I solved it by closing visual studio, reopening visual studio, cleaning and rebuilding the solution. This worked for me.

How to select/get drop down option in Selenium 2

This is the code to select value from the drop down

The value for selectlocator will be the xpath or name of dropdown box, and for optionLocator will have the value to be selected from the dropdown box.

public static boolean select(final String selectLocator,
        final String optionLocator) {
    try {
        element(selectLocator).clear();
        element(selectLocator).sendKeys(Keys.PAGE_UP);
        for (int k = 0; k <= new Select(element(selectLocator))
                .getOptions().size() - 1; k++) {
            combo1.add(element(selectLocator).getValue());
            element(selectLocator).sendKeys(Keys.ARROW_DOWN);
        }
        if (combo1.contains(optionLocator)) {
            element(selectLocator).clear();
            new Select(element(selectLocator)).selectByValue(optionLocator);
            combocheck = element(selectLocator).getValue();
            combo = "";

            return true;
        } else {
            element(selectLocator).clear();
            combo = "The Value " + optionLocator
                    + " Does Not Exist In The Combobox";
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        errorcontrol.add(e.getMessage());
        return false;
    }
}



private static RenderedWebElement element(final String locator) {
    try {

        return (RenderedWebElement) drivers.findElement(by(locator));
    } catch (Exception e) {
        errorcontrol.add(e.getMessage());
        return (RenderedWebElement) drivers.findElement(by(locator));
    }
}

Thanks,

Rekha.

How to install and use "make" in Windows?

Download make.exe from their official site GnuWin32

  • In the Download session, click Complete package, except sources.

  • Follow the installation instructions.

  • Once finished, add the <installation directory>/bin/ to the PATH variable.

Now you will be able to use make in cmd.

Fastest way to list all primes below N

If you have control over N, the very fastest way to list all primes is to precompute them. Seriously. Precomputing is a way overlooked optimization.

Int or Number DataType for DataAnnotation validation attribute

You can write a custom validation attribute:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class Numeric : ValidationAttribute
{
    public Numeric(string errorMessage) : base(errorMessage)
    {
    }

    /// <summary>
    /// Check if given value is numeric
    /// </summary>
    /// <param name="value">The input value</param>
    /// <returns>True if value is numeric</returns>
    public override bool IsValid(object value)
    {
        return decimal.TryParse(value?.ToString(), out _);
    }
}

On your property you can then use the following annotation:

[Numeric("Please fill in a valid number.")]
public int NumberOfBooks { get; set; }

How to set a value for a span using jQuery

You're looking for the wrong selector id:

 $("#submitter").text(submitter_name);

should be

 $("#submittername").text(submitter_name);

python list in sql query as parameter

Easiest way is to turn the list to tuple first

t = tuple(l)
query = "select name from studens where id IN {}".format(t)

How to use if-else logic in Java 8 stream forEach

The problem by using stream().forEach(..) with a call to add or put inside the forEach (so you mutate the external myMap or myList instance) is that you can run easily into concurrency issues if someone turns the stream in parallel and the collection you are modifying is not thread safe.

One approach you can take is to first partition the entries in the original map. Once you have that, grab the corresponding list of entries and collect them in the appropriate map and list.

Map<Boolean, List<Map.Entry<K, V>>> partitions =
    animalMap.entrySet()
             .stream()
             .collect(partitioningBy(e -> e.getValue() == null));

Map<K, V> myMap = 
    partitions.get(false)
              .stream()
              .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

List<K> myList =
    partitions.get(true)
              .stream()
              .map(Map.Entry::getKey) 
              .collect(toList());

... or if you want to do it in one pass, implement a custom collector (assuming a Tuple2<E1, E2> class exists, you can create your own), e.g:

public static <K,V> Collector<Map.Entry<K, V>, ?, Tuple2<Map<K, V>, List<K>>> customCollector() {
    return Collector.of(
            () -> new Tuple2<>(new HashMap<>(), new ArrayList<>()),
            (pair, entry) -> {
                if(entry.getValue() == null) {
                    pair._2.add(entry.getKey());
                } else {
                    pair._1.put(entry.getKey(), entry.getValue());
                }
            },
            (p1, p2) -> {
                p1._1.putAll(p2._1);
                p1._2.addAll(p2._2);
                return p1;
            });
}

with its usage:

Tuple2<Map<K, V>, List<K>> pair = 
    animalMap.entrySet().parallelStream().collect(customCollector());

You can tune it more if you want, for example by providing a predicate as parameter.

Simulate a click on 'a' element using javascript/jquery

Using jQuery:

$('#gift-close').click();

Check whether an array is empty

You can also check it by doing.

if(count($array) > 0)
{
    echo 'Error';
}
else
{
    echo 'No Error';
}

hide div tag on mobile view only?

@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) { #title_message { display: none; }}

This would be for a responsive design with a single page for an iphone screen specifically. Are you actually routing to a different mobile page?

How do you connect to multiple MySQL databases on a single webpage?

<?php
    // Sapan Mohanty
    // Skype:sapan.mohannty
    //***********************************
    $oldData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
    echo mysql_error();
    $NewData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
    echo mysql_error();
    mysql_select_db('OLDDBNAME', $oldData );
    mysql_select_db('NEWDBNAME', $NewData );
    $getAllTablesName    = "SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'";
    $getAllTablesNameExe = mysql_query($getAllTablesName);
    //echo mysql_error();
    while ($dataTableName = mysql_fetch_object($getAllTablesNameExe)) {

        $oldDataCount       = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $oldData);
        $oldDataCountResult = mysql_fetch_object($oldDataCount);


        $newDataCount       = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $NewData);
        $newDataCountResult = mysql_fetch_object($newDataCount);

        if ( $oldDataCountResult->noOfRecord != $newDataCountResult->noOfRecord ) {
            echo "<br/><b>" . $dataTableName->table_name . "</b>";
            echo " | Old: " . $oldDataCountResult->noOfRecord;
            echo " | New: " . $newDataCountResult->noOfRecord;

            if ($oldDataCountResult->noOfRecord < $newDataCountResult->noOfRecord) {
                echo " | <font color='green'>*</font>";

            } else {
                echo " | <font color='red'>*</font>";
            }

            echo "<br/>----------------------------------------";

        }     

    }
    ?>

how to use JSON.stringify and json_decode() properly

jsonText = $_REQUEST['myJSON'];

$decodedText = html_entity_decode($jsonText);

$myArray = json_decode($decodedText, true);`

Automatic confirmation of deletion in powershell

The default is: no prompt.

You can enable it with -Confirm or disable it with -Confirm:$false

However, it will still prompt, when the target:

  • is a directory
  • and it is not empty
  • and the -Recurse parameter is not specified.

-Force is required to also remove hidden and read-only items etc.

To sum it up:

Remove-Item -Recurse -Force -Confirm:$false

...should cover all scenarios.

How to pass arguments to addEventListener listener function?

There is absolutely nothing wrong with the code you've written. Both some_function and someVar should be accessible, in case they were available in the context where anonymous

function() { some_function(someVar); } 

was created.

Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar variable next to the call to addEventListener)

var someVar; 
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Get year, month or day from numpy datetime64

I find the following tricks give between 2x and 4x speed increase versus the pandas method described above (i.e. pd.DatetimeIndex(dates).year etc.). The speed of [dt.year for dt in dates.astype(object)] I find to be similar to the pandas method. Also these tricks can be applied directly to ndarrays of any shape (2D, 3D etc.)

dates = np.arange(np.datetime64('2000-01-01'), np.datetime64('2010-01-01'))
years = dates.astype('datetime64[Y]').astype(int) + 1970
months = dates.astype('datetime64[M]').astype(int) % 12 + 1
days = dates - dates.astype('datetime64[M]') + 1

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

In a pinch, you can disable SSL entirely, or per connection (note this is not recommended for production!) see https://stackoverflow.com/a/19542614/32453

Why do you have to link the math library in C?

Remember that C is an old language and that FPUs are a relatively recent phenomenon. I first saw C on 8-bit processors where it was a lot of work to do even 32-bit integer arithmetic. Many of these implementations didn't even have a floating point math library available!

Even on the first 68000 machines (Mac, Atari ST, Amiga), floating point coprocessors were often expensive add-ons.

To do all that floating point math, you needed a pretty sizable library. And the math was going to be slow. So you rarely used floats. You tried to do everything with integers or scaled integers. When you had to include math.h, you gritted your teeth. Often, you'd write your own approximations and lookup tables to avoid it.

Trade-offs existed for a long time. Sometimes there were competing math packages called "fastmath" or such. What's the best solution for math? Really accurate but slow stuff? Inaccurate but fast? Big tables for trig functions? It wasn't until coprocessors were guaranteed to be in the computer that most implementations became obvious. I imagine that there's some programmer out there somewhere right now, working on an embedded chip, trying to decide whether to bring in the math library to handle some math problem.

That's why math wasn't standard. Many or maybe most programs didn't use a single float. If FPUs had always been around and floats and doubles were always cheap to operate on, no doubt there would have been a "stdmath".

How to clear a textbox using javascript

just get element using

   function name()
   {  
   document.getElementById('elementid').value = "";
   }

you can call this function on onfocus event of textbox and clear the value

Only numbers. Input number in React

 <input
        className="input-Flied2"
        type="TEXT"
        name="userMobileNo"
        placeholder="Moble No"
        value={phonNumber}
        maxLength="10"
        onChange={handleChangeInput}
        required
      />

  const handleChangeInput = (e) => {
const re = /^[0-9\b]+$/; //rules
if (e.target.value === "" || re.test(e.target.value)) {
  setPhoneNumber(e.target.value);
}

};

How to delete columns in numpy.array

Given its name, I think the standard way should be delete:

import numpy as np

A = np.delete(A, 1, 0)  # delete second row of A
B = np.delete(B, 2, 0)  # delete third row of B
C = np.delete(C, 1, 1)  # delete second column of C

According to numpy's documentation page, the parameters for numpy.delete are as follow:

numpy.delete(arr, obj, axis=None)

  • arr refers to the input array,
  • obj refers to which sub-arrays (e.g. column/row no. or slice of the array) and
  • axis refers to either column wise (axis = 1) or row-wise (axis = 0) delete operation.

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

I experienced this issue when I tried to update a Hot Towel Project from the project template and when I created an empty project and installed HotTowel via nuget in VS 2012 as of 10/23/2013.

To fix, I updated via Nuget the Web Api Web Host and Web API packages to 5.0, the current version in NuGet at the moment (10/23/2013).

I then added the binding directs:

<dependentAssembly>
  <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
  <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>

What is the difference between origin and upstream on GitHub?

In a nutshell answer.

  • origin: the fork
  • upstream: the forked

Implicit function declarations in C

Because of historical reasons going back to the very first version of C, functions are assumed to have an implicit definition of int function(int arg1, int arg2, int arg3, etc).

Edit: no, I was wrong about int for the arguments. Instead it passes whatever type the argument is. So it could be an int or a double or a char*. Without a prototype the compiler will pass whatever size the argument is and the function being called had better use the correct argument type to receive it.

For more details look up K&R C.

How to position a Bootstrap popover?

Popover's Viewport (Bootstrap v3)

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

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

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

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

in the following html example:

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

and with CSS:

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

Popover's Boundary (Bootstrap v4)

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

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

How to style HTML5 range input to have different color before and after slider?

If you use first answer, there is a problem with thumb. In chrome if you want the thumb to be larger than the track, then the box shadow overlaps the track with the height of the thumb.

Just sumup all these answers and wrote normally working slider with larger slider thumb: jsfiddle

_x000D_
_x000D_
const slider = document.getElementById("myinput")
const min = slider.min
const max = slider.max
const value = slider.value

slider.style.background = `linear-gradient(to right, red 0%, red ${(value-min)/(max-min)*100}%, #DEE2E6 ${(value-min)/(max-min)*100}%, #DEE2E6 100%)`

slider.oninput = function() {
  this.style.background = `linear-gradient(to right, red 0%, red ${(this.value-this.min)/(this.max-this.min)*100}%, #DEE2E6 ${(this.value-this.min)/(this.max-this.min)*100}%, #DEE2E6 100%)`
};
_x000D_
#myinput {
  border-radius: 8px;
  height: 4px;
  width: 150px;
  outline: none;
  -webkit-appearance: none;
}

input[type='range']::-webkit-slider-thumb {
  width: 6px;
  -webkit-appearance: none;
  height: 12px;
  background: black;
  border-radius: 2px;
}
_x000D_
<div class="chrome">
  <input id="myinput" type="range" min="0" value="25" max="200" />
</div>
_x000D_
_x000D_
_x000D_

Can't run Curl command inside my Docker Container

You don't need to install curl to download the file into Docker container, use ADD command, e.g.

ADD https://raw.githubusercontent.com/Homebrew/install/master/install /tmp
RUN ruby -e /tmp/install

Note: Add above lines to your Dockerfile file.


Another example which installs Azure CLI:

ADD https://aka.ms/InstallAzureCLIDeb /tmp
RUN bash /tmp/InstallAzureCLIDeb

Inserting a value into all possible locations in a list

If you want to insert a list into a list, you can do this:

>>> a = [1,2,3,4,5]
>>> for x in reversed(['a','b','c']): a.insert(2,x)
>>> a
[1, 2, 'a', 'b', 'c', 3, 4, 5]

Delete an element from a dictionary

>>> def delete_key(dict, key):
...     del dict[key]
...     return dict
... 
>>> test_dict = {'one': 1, 'two' : 2}
>>> print delete_key(test_dict, 'two')
{'one': 1}
>>>

this doesn't do any error handling, it assumes the key is in the dict, you might want to check that first and raise if its not

What is the difference between concurrency and parallelism?

Concurrency vs Parallelism

Rob Pike in 'Concurrency Is Not Parallelism'

Concurrency is about dealing with lots of things at once.

Parallelism is about doing lots of things at once.

[Concurrency theory]

Concurrency - handles waiting operation
Parallelism - handles thread stuff

My vision of concurrency and parallelism

enter image description here

[Sync vs Async]

How to find rows that have a value that contains a lowercase letter

I have to add BINARY to the ColumnX, to get result as case sensitive

SELECT * FROM MyTable WHERE BINARY(ColumnX) REGEXP '^[a-z]';

Generate random 5 characters string

I also did not know how to do this until I thought of using PHP array's. And I am pretty sure this is the simplest way of generating a random string or number with array's. The code:

function randstr ($len=10, $abc="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789") {
    $letters = str_split($abc);
    $str = "";
    for ($i=0; $i<=$len; $i++) {
        $str .= $letters[rand(0, count($letters)-1)];
    };
    return $str;
};

You can use this function like this

randstr(20)     // returns a random 20 letter string
                // Or like this
randstr(5, abc) // returns a random 5 letter string using the letters "abc"

Sum one number to every element in a list (or array) in Python

If you don't want list comprehensions:

a = [1,1,1,1,1]
b = []
for i in a:
    b.append(i+1)

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

Look at this post here.

This worked for me:

Delete the files in this folder. vs2010:

 %AppData%\Microsoft\VisualStudio\10.0\ReflectedSchemas

vs2012;

%AppData%\Microsoft\VisualStudio\11.0\ReflectedSchemas

VS Ultimate 2013;

%AppData%\Microsoft\VisualStudio\12.0\ReflectedSchemas

VS Professional 2015;

%AppData%\Microsoft\VisualStudio\14.0\ReflectedSchemas

Reading in a JSON File Using Swift

I’ve used below code to fetch JSON from FAQ-data.json file present in project directory .

I’m implementing in Xcode 7.3 using Swift.

     func fetchJSONContent() {
            if let path = NSBundle.mainBundle().pathForResource("FAQ-data", ofType: "json") {

                if let jsonData = NSData(contentsOfFile: path) {
                    do {
                        if let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {

                            if let responseParameter : NSDictionary = jsonResult["responseParameter"] as? NSDictionary {

                                if let response : NSArray = responseParameter["FAQ"] as? NSArray {
                                    responseFAQ = response
                                    print("response FAQ : \(response)")
                                }
                            }
                        }
                    }
                    catch { print("Error while parsing: \(error)") }
                }
            }
        }

override func viewWillAppear(animated: Bool) {
        fetchFAQContent()
    }

Structure of JSON file :

{
    "status": "00",
    "msg": "FAQ List ",
    "responseParameter": {
        "FAQ": [
            {                
                "question": “Question No.1 here”,
                "answer": “Answer goes here”,  
                "id": 1
            },
            {                
                "question": “Question No.2 here”,
                "answer": “Answer goes here”,
                "id": 2
            }
            . . .
        ]
    }
}

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

Try this:

package my_default;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Test {

    public static void main(String[] args) {
        try {
        // Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook();

        // Get first/desired sheet from the workbook
        XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);

        // XSSFSheet sheet = workbook.getSheetAt(1);//Don't use this line
        // because you get Sheet index (1) is out of range (no sheets)

        //Write some information in the cells or do what you want
        XSSFRow row1 = sheet.createRow(0);
        XSSFCell r1c2 = row1.createCell(0);
        r1c2.setCellValue("NAME");
        XSSFCell r1c3 = row1.createCell(1);
        r1c3.setCellValue("AGE");


        //Save excel to HDD Drive
        File pathToFile = new File("D:\\test.xlsx");
        if (!pathToFile.exists()) {
            pathToFile.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(pathToFile);
        workbook.write(fos);
        fos.close();
        System.out.println("Done");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
    XSSFSheet sheet = null;
    int count = 0;

    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        String sName = wb.getSheetName(i);
        if (sName.startsWith(prefix))
            count++;
    }

    if (count > 0) {
        sheet = wb.createSheet(prefix + count);
    } else
        sheet = wb.createSheet(prefix);

    if (isHidden)
        wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);

        return sheet;
    }

}

How to assign the output of a Bash command to a variable?

In this specific case, note that bash has a variable called PWD that contains the current directory: $PWD is equivalent to `pwd`. (So do other shells, this is a standard feature.) So you can write your script like this:

#!/bin/bash
until [ "$PWD" = "/" ]; do
  echo "$PWD"
  ls && cd .. && ls 
done

Note the use of double quotes around the variable references. They are necessary if the variable (here, the current directory) contains whitespace or wildcards (\[?*), because the shell splits the result of variable expansions into words and performs globbing on these words. Always double-quote variable expansions "$foo" and command substitutions "$(foo)" (unless you specifically know you have not to).

In the general case, as other answers have mentioned already:

  • You can't use whitespace around the equal sign in an assignment: var=value, not var = value
  • The $ means “take the value of this variable”, so you don't use it when assigning: var=value, not $var=value.

How to pause in C?

I assume you are on Windows. Instead of trying to run your program by double clicking on it's icon or clicking a button in your IDE, open up a command prompt, cd to the directory your program is in, and run it by typing its name on the command line.

Something better than .NET Reflector?

In my opinion, there are three serious alternatives to keep an eye on, all of which are free:

  • ILSpy: This is from the same people who make the (also free) SharpDevelop IDE. As well as being free, it is also open source. An additional extension they are working on is the ability to debug decompiled code (something which the pro version of Reflector can do), which works surprisingly well.
  • JustDecompile: A standalone decompiler from Telerik (announced today, currently in Beta).
  • dotPeek: A standalone decompiler from JetBrains (available standalone as part of an EAP at the moment).

All of these approach the problem in slightly different ways with differing UIs. I would suggest giving them all a try and seeing which one you prefer.

How to export a CSV to Excel using Powershell

This is a slight variation that worked better for me.

$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"

$xl = new-object -comobject excel.application
$xl.visible = $false
$Workbook = $xl.workbooks.open($CSV)
$Worksheets = $Workbooks.worksheets

$Workbook.SaveAs($XLS,1)
$Workbook.Saved = $True

$xl.Quit()

.prop('checked',false) or .removeAttr('checked')?

Another alternative to do the same thing is to filter on type=checkbox attribute:

$('input[type="checkbox"]').removeAttr('checked');

or

$('input[type="checkbox"]').prop('checked' , false);

Remeber that The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

Know more...

Port 443 in use by "Unable to open process" with PID 4

I had the same problem. Another way to solve this problem when running XAMPP on Windows:

  1. Open a CMD prompt and type in command: net stop was /y

  2. Run Dialog Box (press keys Win+R) .. then type: services.msc

I then scrolled down to: World Wide Web Publishing Service Double clicked on it and clicked STOP (if this service status is Started)

3.Start Apache again with XAMPP :)

Link Ref: http://www.sitepoint.com/unblock-port-80-on-windows-run-apache/

How do I make bootstrap table rows clickable?

Using jQuery it's quite trivial. v2.0 uses the table class on all tables.

$('.table > tbody > tr').click(function() {
    // row was clicked
});

Maven dependency update on commandline

If you just want to re-load/update dependencies (I assume, with constantly changing you mean either SNAPSHOTS or local dependencies you update yourself), you can use

mvn dependency:resolve

How do I log a Python error with debug information?

If "debugging information" means the values present when exception was raised, then logging.exception(...) won't help. So you'll need a tool that logs all variable values along with the traceback lines automatically.

Out of the box you'll get log like

2020-03-30 18:24:31 main ERROR   File "./temp.py", line 13, in get_ratio
2020-03-30 18:24:31 main ERROR     return height / width
2020-03-30 18:24:31 main ERROR       height = 300
2020-03-30 18:24:31 main ERROR       width = 0
2020-03-30 18:24:31 main ERROR builtins.ZeroDivisionError: division by zero

Have a look at some pypi tools, I'd name:

Some of them give you pretty crash messages: enter image description here

But you might find some more on pypi

What is Hash and Range Primary Key?

"Hash and Range Primary Key" means that a single row in DynamoDB has a unique primary key made up of both the hash and the range key. For example with a hash key of X and range key of Y, your primary key is effectively XY. You can also have multiple range keys for the same hash key but the combination must be unique, like XZ and XA. Let's use their examples for each type of table:

Hash Primary Key – The primary key is made of one attribute, a hash attribute. For example, a ProductCatalog table can have ProductID as its primary key. DynamoDB builds an unordered hash index on this primary key attribute.

This means that every row is keyed off of this value. Every row in DynamoDB will have a required, unique value for this attribute. Unordered hash index means what is says - the data is not ordered and you are not given any guarantees into how the data is stored. You won't be able to make queries on an unordered index such as Get me all rows that have a ProductID greater than X. You write and fetch items based on the hash key. For example, Get me the row from that table that has ProductID X. You are making a query against an unordered index so your gets against it are basically key-value lookups, are very fast, and use very little throughput.


Hash and Range Primary Key – The primary key is made of two attributes. The first attribute is the hash attribute and the second attribute is the range attribute. For example, the forum Thread table can have ForumName and Subject as its primary key, where ForumName is the hash attribute and Subject is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.

This means that every row's primary key is the combination of the hash and range key. You can make direct gets on single rows if you have both the hash and range key, or you can make a query against the sorted range index. For example, get Get me all rows from the table with Hash key X that have range keys greater than Y, or other queries to that affect. They have better performance and less capacity usage compared to Scans and Queries against fields that are not indexed. From their documentation:

Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false

I probably missed some things as I typed this out and I only scratched the surface. There are a lot more aspects to take into consideration when working with DynamoDB tables (throughput, consistency, capacity, other indices, key distribution, etc.). You should take a look at the sample tables and data page for examples.

'router-outlet' is not a known element

It works for me, when i add following code in app.module.ts

@NgModule({
...,
   imports: [
     AppRoutingModule
    ],
...
})

Subprocess check_output returned non-zero exit status 1

For Windows users: Try deleting files: java.exe, javaw.exe and javaws.exe from Windows\System32

My issue was the java version 1.7 installed.

Delete all files of specific type (extension) recursively down a directory using a batch file

You can use this to delete ALL Files Inside a Folder and Subfolders:

DEL "C:\Folder\*.*" /S /Q

Or use this to Delete Certain File Types Only:

DEL "C:\Folder\*.mp4" /S /Q 
DEL "C:\Folder\*.dat" /S /Q 

Maven not found in Mac OSX mavericks

brew install maven

Please ensure that you've installed the latest Xcode and Command Line tools.

xcode-select --install

Avoid browser popup blockers

I tried multiple solutions, but his is the only one that actually worked for me in all the browsers

let newTab = window.open(); newTab.location.href = url;

How to load a UIView using a nib file created with Interface Builder

I would use UINib to instantiate a custom UIView to be reused

UINib *customNib = [UINib nibWithNibName:@"MyCustomView" bundle:nil];
MyCustomViewClass *customView = [[customNib instantiateWithOwner:self options:nil] objectAtIndex:0];
[self.view addSubview:customView];

Files needed in this case are MyCustomView.xib, MyCustomViewClass.h and MyCustomViewClass.m Note that [UINib instantiateWithOwner] returns an array, so you should use the element which reflects the UIView you want to re-use. In this case it's the first element.

How to set selected value of jquery select2?

This may help someone loading select2 data from AJAX while loading data for editing (applicable for single or multi-select):

During my form/model load :

  $.ajax({
        type: "POST",
        ...        
        success: function (data) {
          selectCountries(fixedEncodeURI(data.countries));
         }

Call to select data for Select2:

var countrySelect = $('.select_country');
function selectCountries(countries)
    {
        if (countries) {
            $.ajax({
                type: 'GET',
                url: "/regions/getCountries/",
                data: $.param({ 'idsSelected': countries }, true),

            }).then(function (data) {
                // create the option and append to Select2                     
                $.each(data, function (index, value) {
                    var option = new Option(value.text, value.id, true, true);
                    countrySelect.append(option).trigger('change');
                    console.log(option);
                });
                // manually trigger the `select2:select` event
                countrySelect.trigger({
                    type: 'select2:select',
                    params: {
                        data: data
                    }
                });
            });
        }
    }

and if you may be having issues with encoding you may change as your requirement:

function fixedEncodeURI(str) {
        return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/%22/g,"");

    }

Create hyperlink to another sheet

This is the code I use for creating an index sheet.

Sub CreateIndexSheet()
    Dim wSheet As Worksheet
    ActiveWorkbook.Sheets.Add(Before:=Worksheets(1)).Name = "Contents" 'Call whatever you like
    Range("A1").Select
    Application.ScreenUpdating = False 'Prevents seeing all the flashing as it updates the sheet
    For Each wSheet In Worksheets
        ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="'" & wSheet.Name & "'" & "!A1", TextToDisplay:=wSheet.Name
        ActiveCell.Offset(1, 0).Select 'Moves down a row
    Next
    Range("A1").EntireColumn.AutoFit
    Range("A1").EntireRow.Delete 'Remove content sheet from content list
    Application.ScreenUpdating = True
End Sub

How to create a button programmatically?

enter image description here

 func viewDidLoad(){
                    saveActionButton = UIButton(frame: CGRect(x: self.view.frame.size.width - 60, y: 0, width: 50, height: 50))
                    self.saveActionButton.backgroundColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 0.7)
                    saveActionButton.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
                    self.saveActionButton.setTitle("Done", for: .normal)
                    self.saveActionButton.layer.cornerRadius = self.saveActionButton.frame.size.width / 2
                    self.saveActionButton.layer.borderColor = UIColor.darkGray.cgColor
                    self.saveActionButton.layer.borderWidth = 1
                    self.saveActionButton.center.y = self.view.frame.size.height - 80
                    self.view.addSubview(saveActionButton)
        }

          func doneAction(){
          print("Write your own logic")
         }

Convert number to varchar in SQL with formatting

RIGHT('00' + CONVERT(VARCHAR, MyNumber), 2)

Be warned that this will cripple numbers > 99. You might want to factor in that possibility.

How to invoke the super constructor in Python?

Short Answer

super(DerivedClass, self).__init__()

Long Answer

What does super() do?

It takes specified class name, finds its base classes (Python allows multiple inheritance) and looks for the method (__init__ in this case) in each of them from left to right. As soon as it finds method available, it will call it and end the search.

How do I call init of all base classes?

Above works if you have only one base class. But Python does allow multiple inheritance and you might want to make sure all base classes are initialized properly. To do that, you should have each base class call init:

class Base1:
  def __init__():
    super(Base1, self).__init__()

class Base2:
  def __init__():
    super(Base2, self).__init__()

class Derived(Base1, Base2):
  def __init__():
    super(Derived, self).__init__()

What if I forget to call init for super?

The constructor (__new__) gets invoked in a chain (like in C++ and Java). Once the instance is created, only that instance's initialiser (__init__) is called, without any implicit chain to its superclass.

How to pass credentials to the Send-MailMessage command for sending emails

So..it was SSL problem. Whatever I was doing was absolutely correct. Only that I was not using the ssl option. So I added "-Usessl true" to my original command and it worked.

PHP Fatal Error Failed opening required File

Just in case this helps anybody else out there, I stumbled on an obscure case for this error triggering last night. Specifically, I was using the require_once method and specifying only a filename and no path, since the file being required was present in the same directory.

I started to get the 'Failed opening required file' error at one point. After tearing my hair out for a while, I finally noticed a PHP Warning message immediately above the fatal error output, indicating 'failed to open stream: Permission denied', but more importantly, informing me of the path to the file it was trying to open. I then twigged to the fact I had created a copy of the file (with ownership not accessible to Apache) elsewhere that happened to also be in the PHP 'include' search path, and ahead of the folder where I wanted it to be picked up. D'oh!

How to access the GET parameters after "?" in Express?

In my case with the given code, I was able to parse the value of the passed parameter in this way.

_x000D_
_x000D_
const express = require('express');
const bodyParser = require('body-parser');

const app = express(); 
app.use(bodyParser.urlencoded({ extended: false }));
//url/par1=val1&par2=val2 
let val1= req.body.par1;
let val2 = req.body.par2;
_x000D_
_x000D_
_x000D_

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

When you include the '.' you are essentially giving the "full path" to the executable bash script, so your shell does not need to check your PATH variable. Without the '.' your shell will look in your PATH variable (which you can see by running echo $PATH to see if the command you typed lives in any of the folders on your PATH. If it doesn't (as is the case with manage.py) it says it can't find the file. It is considered bad practice to include the current directory on your PATH, which is explained reasonably well here: http://www.faqs.org/faqs/unix-faq/faq/part2/section-13.html

Can anyone recommend a simple Java web-app framework?

Haven't tried it myself, but I think

http://www.playframework.org/

has a lot of potential...

coming from php and classic asp, it's the first java web framework that sounds promising to me....

Edit by original question asker - 2011-06-09

Just wanted to provide an update.

I went with Play and it was exactly what I asked for. It requires very little configuration, and just works out of the box. It is unusual in that it eschews some common Java best-practices in favor of keeping things as simple as possible.

In particular, it makes heavy use of static methods, and even does some introspection on the names of variables passed to methods, something not supported by the Java reflection API.

Play's attitude is that its first goal is being a useful web framework, and sticking to common Java best-practices and idioms is secondary to that. This approach makes sense to me, but Java purists may not like it, and would be better-off with Apache Wicket.

In summary, if you want to build a web-app with convenience and simplicity comparable to a framework like Ruby on Rails, but in Java and with the benefit of Java's tooling (eg. Eclipse), then Play Framework is a great choice.

How to read a value from the Windows registry

Since Windows >=Vista/Server 2008, RegGetValue is available, which is a safer function than RegQueryValueEx. No need for RegOpenKeyEx, RegCloseKey or NUL termination checks of string values (REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ).

#include <iostream>
#include <string>
#include <exception>
#include <windows.h>

/*! \brief                          Returns a value from HKLM as string.
    \exception  std::runtime_error  Replace with your error handling.
*/
std::wstring GetStringValueFromHKLM(const std::wstring& regSubKey, const std::wstring& regValue)
{
    size_t bufferSize = 0xFFF; // If too small, will be resized down below.
    std::wstring valueBuf; // Contiguous buffer since C++11.
    valueBuf.resize(bufferSize);
    auto cbData = static_cast<DWORD>(bufferSize * sizeof(wchar_t));
    auto rc = RegGetValueW(
        HKEY_LOCAL_MACHINE,
        regSubKey.c_str(),
        regValue.c_str(),
        RRF_RT_REG_SZ,
        nullptr,
        static_cast<void*>(valueBuf.data()),
        &cbData
    );
    while (rc == ERROR_MORE_DATA)
    {
        // Get a buffer that is big enough.
        cbData /= sizeof(wchar_t);
        if (cbData > static_cast<DWORD>(bufferSize))
        {
            bufferSize = static_cast<size_t>(cbData);
        }
        else
        {
            bufferSize *= 2;
            cbData = static_cast<DWORD>(bufferSize * sizeof(wchar_t));
        }
        valueBuf.resize(bufferSize);
        rc = RegGetValueW(
            HKEY_LOCAL_MACHINE,
            regSubKey.c_str(),
            regValue.c_str(),
            RRF_RT_REG_SZ,
            nullptr,
            static_cast<void*>(valueBuf.data()),
            &cbData
        );
    }
    if (rc == ERROR_SUCCESS)
    {
        cbData /= sizeof(wchar_t);
        valueBuf.resize(static_cast<size_t>(cbData - 1)); // remove end null character
        return valueBuf;
    }
    else
    {
        throw std::runtime_error("Windows system error code: " + std::to_string(rc));
    }
}

int main()
{
    std::wstring regSubKey;
#ifdef _WIN64 // Manually switching between 32bit/64bit for the example. Use dwFlags instead.
    regSubKey = L"SOFTWARE\\WOW6432Node\\Company Name\\Application Name\\";
#else
    regSubKey = L"SOFTWARE\\Company Name\\Application Name\\";
#endif
    std::wstring regValue(L"MyValue");
    std::wstring valueFromRegistry;
    try
    {
        valueFromRegistry = GetStringValueFromHKLM(regSubKey, regValue);
    }
    catch (std::exception& e)
    {
        std::cerr << e.what();
    }
    std::wcout << valueFromRegistry;
}

Its parameter dwFlags supports flags for type restriction, filling the value buffer with zeros on failure (RRF_ZEROONFAILURE) and 32/64bit registry access (RRF_SUBKEY_WOW6464KEY, RRF_SUBKEY_WOW6432KEY) for 64bit programs.

regular expression for finding 'href' value of a <a> link

Try this :

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var res = Find(html);
        }

        public static List<LinkItem> Find(string file)
        {
            List<LinkItem> list = new List<LinkItem>();

            // 1.
            // Find all matches in file.
            MatchCollection m1 = Regex.Matches(file, @"(<a.*?>.*?</a>)",
                RegexOptions.Singleline);

            // 2.
            // Loop over each match.
            foreach (Match m in m1)
            {
                string value = m.Groups[1].Value;
                LinkItem i = new LinkItem();

                // 3.
                // Get href attribute.
                Match m2 = Regex.Match(value, @"href=\""(.*?)\""",
                RegexOptions.Singleline);
                if (m2.Success)
                {
                    i.Href = m2.Groups[1].Value;
                }

                // 4.
                // Remove inner tags from text.
                string t = Regex.Replace(value, @"\s*<.*?>\s*", "",
                RegexOptions.Singleline);
                i.Text = t;

                list.Add(i);
            }
            return list;
        }

        public struct LinkItem
        {
            public string Href;
            public string Text;

            public override string ToString()
            {
                return Href + "\n\t" + Text;
            }
        }

    }  

Input:

  string html = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> 2.<a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> "; 

Result:

[0] = {www.aaa.xx/xx.zz?id=xxxx&name=xxxx}
[1] = {http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx}

C# Scraping HTML Links

Scraping HTML extracts important page elements. It has many legal uses for webmasters and ASP.NET developers. With the Regex type and WebClient, we implement screen scraping for HTML.

Edited

Another easy way:you can use a web browser control for getting href from tag a,like this:(see my example)

 public Form1()
        {
            InitializeComponent();
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.DocumentText = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"https://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"www.aaa.xx/xx.zz/xxx\" ....></a>";
        }

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            List<string> href = new List<string>();
            foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("a"))
            {
                href.Add(el.GetAttribute("href"));
            }
        }

Generating random strings with T-SQL

I realize that this is an old question with many fine answers. However when I found this I also found a more recent article on TechNet by Saeid Hasani

T-SQL: How to Generate Random Passwords

While the solution focuses on passwords it applies to the general case. Saeid works through various considerations to arrive at a solution. It is very instructive.

A script containing all the code blocks form the article is separately available via the TechNet Gallery, but I would definitely start at the article.

Print text instead of value from C enum

The question is you want write the name just one times.
I have an ider like this:

#define __ENUM(situation,num) \
    int situation = num;        const char * __##situation##_name = #situation;

    const struct {
        __ENUM(get_other_string, -203);//using a __ENUM Mirco make it ease to write, 
        __ENUM(get_negative_to_unsigned, -204);
        __ENUM(overflow,-205);
//The following two line showing the expanding for __ENUM
        int get_no_num = -201;      const char * __get_no_num_name = "get_no_num";
        int get_float_to_int = -202;        const char * get_float_to_int_name = "float_to_int_name";

    }eRevJson;
#undef __ENUM
    struct sIntCharPtr { int value; const char * p_name; };
//This function transform it to string.
    inline const char * enumRevJsonGetString(int num) {
        sIntCharPtr * ptr = (sIntCharPtr *)(&eRevJson);
        for (int i = 0;i < sizeof(eRevJson) / sizeof(sIntCharPtr);i++) {
            if (ptr[i].value == num) {
                return ptr[i].p_name;
            }
        }
        return "bad_enum_value";
    }

it uses a struct to insert enum, so that a printer to string could follows each enum value define.

int main(int argc, char *argv[]) {  
    int enum_test = eRevJson.get_other_string;
    printf("error is %s, number is %d\n", enumRevJsonGetString(enum_test), enum_test);

>error is get_other_string, number is -203

The difference to enum is builder can not report error if the numbers are repeated. if you don't like write number, __LINE__ could replace it:

#define ____LINE__ __LINE__
#define __ENUM(situation) \
    int situation = (____LINE__ - __BASELINE -2);       const char * __##situation##_name = #situation;
constexpr int __BASELINE = __LINE__;
constexpr struct {
    __ENUM(Sunday);
    __ENUM(Monday);
    __ENUM(Tuesday);
    __ENUM(Wednesday);
    __ENUM(Thursday);
    __ENUM(Friday);
    __ENUM(Saturday);
}eDays;
#undef __ENUM
inline const char * enumDaysGetString(int num) {
    sIntCharPtr * ptr = (sIntCharPtr *)(&eDays);
    for (int i = 0;i < sizeof(eDays) / sizeof(sIntCharPtr);i++) {
        if (ptr[i].value == num) {
            return ptr[i].p_name;
        }
    }
    return "bad_enum_value";
}
int main(int argc, char *argv[]) {  
    int d = eDays.Wednesday;
    printf("day %s, number is %d\n", enumDaysGetString(d), d);
    d = 1;
    printf("day %s, number is %d\n", enumDaysGetString(d), d);
}

>day Wednesday, number is 3 >day Monday, number is 1

Custom designing EditText

edit_text.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ffffff" />
    <corners android:radius="5dp"/>
    <stroke android:width="2dip" android:color="@color/button_color_submit" />
</shape>

use here

<EditText
 -----
 ------
 android:background="@drawable/edit_text.xml"
/>

python - find index position in list based of partial string

Your idea to use enumerate() was correct.

indices = []
for i, elem in enumerate(mylist):
    if 'aa' in elem:
        indices.append(i)

Alternatively, as a list comprehension:

indices = [i for i, elem in enumerate(mylist) if 'aa' in elem]

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

You're not adding columns to your DataGridView

DataGridView dataGridView1 = new DataGridView();//Create new grid

dataGridView1.Columns[0].Name = "ItemID";// refer to column which is not there 

Is it clear now why you get an exception?

Add this line before you use columns to fix the error

dataGridView1.ColumnCount = 5;

Example to use shared_ptr?

I will add that one of the important things about shared_ptr's is to only ever construct them with the following syntax:

shared_ptr<Type>(new Type(...));

This way, the "real" pointer to Type is anonymous to your scope, and held only by the shared pointer. Thus it will be impossible for you to accidentally use this "real" pointer. In other words, never do this:

Type* t_ptr = new Type(...);
shared_ptr<Type> t_sptr ptrT(t_ptr);
//t_ptr is still hanging around!  Don't use it!

Although this will work, you now have a Type* pointer (t_ptr) in your function which lives outside the shared pointer. It's dangerous to use t_ptr anywhere, because you never know when the shared pointer which holds it may destruct it, and you'll segfault.

Same goes for pointers returned to you by other classes. If a class you didn't write hands you a pointer, it's generally not safe to just put it in a shared_ptr. Not unless you're sure that the class is no longer using that object. Because if you do put it in a shared_ptr, and it falls out of scope, the object will get freed when the class may still need it.

Turning error reporting off php

Tried this yet?

error_reporting(0);
@ini_set('display_errors', 0);

How to test REST API using Chrome's extension "Advanced Rest Client"

This seems a very old question, but I am providing an answer, so that it might help others. You can specify the variables in the second screen in the form section, as shown below or in the RAW format by appending the variables as shown in the second image.

Specify Form Variables

Specify in RAW format

If your variable and variable values are valid, you should see a successful response in the response section.

How to make a rest post call from ReactJS code?

I think this way also a normal way. But sorry, I can't describe in English ((

_x000D_
_x000D_
    submitHandler = e => {_x000D_
    e.preventDefault()_x000D_
    console.log(this.state)_x000D_
    fetch('http://localhost:5000/questions',{_x000D_
        method: 'POST',_x000D_
        headers: {_x000D_
            Accept: 'application/json',_x000D_
                    'Content-Type': 'application/json',_x000D_
        },_x000D_
        body: JSON.stringify(this.state)_x000D_
    }).then(response => {_x000D_
            console.log(response)_x000D_
        })_x000D_
        .catch(error =>{_x000D_
            console.log(error)_x000D_
        })_x000D_
    _x000D_
}
_x000D_
_x000D_
_x000D_

https://googlechrome.github.io/samples/fetch-api/fetch-post.html

fetch('url/questions',{ method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(this.state) }).then(response => { console.log(response) }) .catch(error =>{ console.log(error) })

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

I had similar issue while running emulator on mac os. After lot of struggle I found that I had incorrect sdk path set in .bash_profile. I have two installations of android and it was causing that issue. I managed to fix by matching ANDROID_SDK_ROOT path in .bash_profile with sdk I am using inside android studio.

IIS AppPoolIdentity and file system write access permissions

Each application pool in IIs creates its own secure user folder with FULL read/write permission by default under c:\users. Open up your Users folder and see what application pool folders are there, right click, and check their rights for the application pool virtual account assigned. You should see your application pool account added already with read/write access assigned to its root and subfolders.

So that type of file storage access is automatically done and you should be able to write whatever you like there in the app pools user account folders without changing anything. That's why virtual user accounts for each application pool were created.

jQuery override default validation error message display (Css) Popup/Tooltip like

Add following css to your .validate method to change the css or functionality

 errorElement: "div",
    wrapper: "div",
    errorPlacement: function(error, element) {
        offset = element.offset();
        error.insertAfter(element)
        error.css('color','red');
    }

How do I use a third-party DLL file in Visual Studio C++?

I'f you're suppsed to be able to use it, then 3rd-party library should have a *.lib file as well as a *.dll file. You simply need to add the *.lib to the list of input file in your project's 'Linker' options.

This *.lib file isn't necessarily a 'static' library (which contains code): instead a *.lib can be just a file that links your executable to the DLL.

jquery - disable click

/** eworkyou **//

$('#navigation a').bind('click',function(e){

    var $this   = $(this);
    var prev    = current;

    current = $this.parent().index() + 1; //

    if (current == 1){
    $("#navigation a:eq(1)").unbind("click"); // 
    }
    if (current >= 2){
    $("#navigation a:eq(1)").bind("click"); // 
    }

Delete a single record from Entity Framework?

You can do something like this in your click or celldoubleclick event of your grid(if you used one)

if(dgEmp.CurrentRow.Index != -1)
 {
    employ.Id = (Int32)dgEmp.CurrentRow.Cells["Id"].Value;
    //Some other stuff here
 }

Then do something like this in your Delete Button:

using(Context context = new Context())
{
     var entry = context.Entry(employ);
     if(entry.State == EntityState.Detached)
     {
        //Attached it since the record is already being tracked
        context.Employee.Attach(employ);
     }                             
     //Use Remove method to remove it virtually from the memory               
     context.Employee.Remove(employ);
     //Finally, execute SaveChanges method to finalized the delete command 
     //to the actual table
     context.SaveChanges();

     //Some stuff here
}

Alternatively, you can use a LINQ Query instead of using LINQ To Entities Query:

var query = (from emp in db.Employee
where emp.Id == employ.Id
select emp).Single();

employ.Id is used as filtering parameter which was already passed from the CellDoubleClick Event of your DataGridView.

Logging in Scala

You should have a look at the scalax library : http://scalax.scalaforge.org/ In this library, there is a Logging trait, using sl4j as backend. By using this trait, you can log quite easily (just use the logger field in the class inheriting the trait).

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

You can browse package folder below method.

  1. Use Sublime Text 2 menu : Preferences\Browse Packages
  2. In Windows 7 : C:\Users\%username%\AppData\Roaming\Sublime Text 2\Packages (equals %appdata%\Sublime Text 2\Packages)

Activity restart on rotation Android

Note: I post this answer if someone in the future face the same problem as me. For me the following line wasn't enought:

android:configChanges="orientation"

When I rotated the screen, the method `onConfigurationChanged(Configuration newConfig) did't get called.

Solution: I also had to add "screenSize" even if the problem had to do with the orientation. So in the AndroidManifest.xml - file, add this:

android:configChanges="keyboardHidden|orientation|screenSize"

Then implement the method onConfigurationChanged(Configuration newConfig)

How to check version of python modules?

Use pip show to find the version!

# in order to get package version execute the below command
pip show YOUR_PACKAGE_NAME | grep Version

Difference between java.exe and javaw.exe

java.exe is the command where it waits for application to complete untill it takes the next command. javaw.exe is the command which will not wait for the application to complete. you can go ahead with another commands.

How do I use the Tensorboard callback of Keras?

Change

keras.callbacks.TensorBoard(log_dir='/Graph', histogram_freq=0,  
          write_graph=True, write_images=True)

to

tbCallBack = keras.callbacks.TensorBoard(log_dir='Graph', histogram_freq=0,  
          write_graph=True, write_images=True)

and set your model

tbCallback.set_model(model)

Run in your terminal

tensorboard  --logdir Graph/

Preview an image before it is uploaded

Here's a multiple files version, based on Ivan Baev's answer.

The HTML

<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>

JavaScript / jQuery

$(function() {
    // Multiple images preview in browser
    var imagesPreview = function(input, placeToInsertImagePreview) {

        if (input.files) {
            var filesAmount = input.files.length;

            for (i = 0; i < filesAmount; i++) {
                var reader = new FileReader();

                reader.onload = function(event) {
                    $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                }

                reader.readAsDataURL(input.files[i]);
            }
        }

    };

    $('#gallery-photo-add').on('change', function() {
        imagesPreview(this, 'div.gallery');
    });
});

Requires jQuery 1.8 due to the usage of $.parseHTML, which should help with XSS mitigation.

This will work out of the box, and the only dependancy you need is jQuery.

error_log per Virtual Host?

Create Simple VirtualHost:

example hostname:- thecontrolist.localhost

  1. C:\Windows\System32\drivers\etc

    127.0.0.1 thecontrolist.localhost in hosts file

  2. C:\xampp\apache\conf\extra\httpd-vhosts.conf

    <VirtualHost *>
      ServerName thecontrolist.localhost
      ServerAlias thecontrolist.localhost
      DocumentRoot "/xampp/htdocs/thecontrolist"
      <Directory "/xampp/htdocs/thecontrolist">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
      </Directory>
    </VirtualHost>
    
  3. Don't Forget to restart Your apache. for more check this link

Uploading images using Node.js, Express, and Mongoose

See, the best thing you can do is to just upload the image to the disk and save the URL in MongoDB. Rest when you retrieve the image again. Just specify the URL, and you will get an image. The code for uploading is as follows.

app.post('/upload', function(req, res) {
    // Get the temporary location of the file
    var tmp_path = req.files.thumbnail.path;
    // Set where the file should actually exists - in this case it is in the "images" directory.
    target_path = '/tmp/' + req.files.thumbnail.name;
    // Move the file from the temporary location to the intended location
    fs.rename(tmp_path, target_path, function(err) {
        if (err)
            throw err;
        // Delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files.
        fs.unlink(tmp_path, function() {
            if (err)
                throw err;
            //
        });
    });
});

Now save the target path in your MongoDB database.

Again, while retrieving the image, just extract the URL from the MongoDB database, and use it on this method.

fs.readFile(target_path, "binary", function(error, file) {
    if(error) {
        res.writeHead(500, {"Content-Type": "text/plain"});
        res.write(error + "\n");
        res.end();
    }
    else {
        res.writeHead(200, {"Content-Type": "image/png"});
        res.write(file, "binary");
    }
});

Can I draw rectangle in XML?

Quick and dirty way:

<View
    android:id="@+id/colored_bar"
    android:layout_width="48dp"
    android:layout_height="3dp"
    android:background="@color/bar_red" />

Are string.Equals() and == operator really same?

Two differences:

  • Equals is polymorphic (i.e. it can be overridden, and the implementation used will depend on the execution-time type of the target object), whereas the implementation of == used is determined based on the compile-time types of the objects:

    // Avoid getting confused by interning
    object x = new StringBuilder("hello").ToString();
    object y = new StringBuilder("hello").ToString();
    if (x.Equals(y)) // Yes
    
    // The compiler doesn't know to call ==(string, string) so it generates
    // a reference comparision instead
    if (x == y) // No
    
    string xs = (string) x;
    string ys = (string) y;
    
    // Now *this* will call ==(string, string), comparing values appropriately
    if (xs == ys) // Yes
    
  • Equals will go bang if you call it on null, == won't

    string x = null;
    string y = null;
    
    if (x.Equals(y)) // Bang
    
    if (x == y) // Yes
    

Note that you can avoid the latter being a problem using object.Equals:

if (object.Equals(x, y)) // Fine even if x or y is null

How can I check if character in a string is a letter? (Python)

This works:

word = str(input("Enter string:"))
notChar = 0
isChar = 0
for char in word:
    if not char.isalpha():
        notChar += 1
    else:
        isChar += 1
print(isChar, " were letters; ", notChar, " were not letters.")

Correct way to quit a Qt program?

If you're using Qt Jambi, this should work:

QApplication.closeAllWindows();

git clone from another directory

It's as easy as it looks.

14:27:05 ~$ mkdir gittests
14:27:11 ~$ cd gittests/
14:27:13 ~/gittests$ mkdir localrepo
14:27:20 ~/gittests$ cd localrepo/
14:27:21 ~/gittests/localrepo$ git init
Initialized empty Git repository in /home/andwed/gittests/localrepo/.git/
14:27:22 ~/gittests/localrepo (master #)$ cd ..
14:27:35 ~/gittests$ git clone localrepo copyoflocalrepo
Cloning into 'copyoflocalrepo'...
warning: You appear to have cloned an empty repository.
done.
14:27:42 ~/gittests$ cd copyoflocalrepo/
14:27:46 ~/gittests/copyoflocalrepo (master #)$ git status
On branch master

Initial commit

nothing to commit (create/copy files and use "git add" to track)
14:27:46 ~/gittests/copyoflocalrepo (master #)$