Programs & Examples On #Struts config

Use this question for struts-config related questions.

ASP.NET MVC Ajax Error handling

I did a quick solution because I was short of time and it worked ok. Although I think the better option is use an Exception Filter, maybe my solution can help in the case that a simple solution is needed.

I did the following. In the controller method I returned a JsonResult with a property "Success" inside the Data:

    [HttpPut]
    public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave) 
    {
        if (!ModelState.IsValid)
        {
            return new JsonResult
            {
                Data = new { ErrorMessage = "Model is not valid", Success = false },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }
        try
        {
            MyDbContext db = new MyDbContext();

            db.Entry(employeToSave).State = EntityState.Modified;
            db.SaveChanges();

            DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];

            if (employeToSave.Id == user.Id)
            {
                user.Company = employeToSave.Company;
                user.Language = employeToSave.Language;
                user.Money = employeToSave.Money;
                user.CostCenter = employeToSave.CostCenter;

                Session["EmployeLoggin"] = user;
            }
        }
        catch (Exception ex) 
        {
            return new JsonResult
            {
                Data = new { ErrorMessage = ex.Message, Success = false },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }

        return new JsonResult() { Data = new { Success = true }, };
    }

Later in the ajax call I just asked for this property to know if I had an exception:

$.ajax({
    url: 'UpdateEmployeeConfig',
    type: 'PUT',
    data: JSON.stringify(EmployeConfig),
    contentType: "application/json;charset=utf-8",
    success: function (data) {
        if (data.Success) {
            //This is for the example. Please do something prettier for the user, :)
            alert('All was really ok');                                           
        }
        else {
            alert('Oups.. we had errors: ' + data.ErrorMessage);
        }
    },
    error: function (request, status, error) {
       alert('oh, errors here. The call to the server is not working.')
    }
});

Hope this helps. Happy code! :P

How to get the body's content of an iframe in Javascript?

The exact question is how to do it with pure JavaScript not with jQuery.

But I always use the solution that can be found in jQuery's source code. It's just one line of native JavaScript.

For me it's the best, easy readable and even afaik the shortest way to get the iframes content.

First get your iframe

var iframe = document.getElementById('id_description_iframe');

// or
var iframe = document.querySelector('#id_description_iframe');

And then use jQuery's solution

var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

It works even in the Internet Explorer which does this trick during the contentWindow property of the iframe object. Most other browsers uses the contentDocument property and that is the reason why we proof this property first in this OR condition. If it is not set try contentWindow.document.

Select elements in iframe

Then you can usually use getElementById() or even querySelectorAll() to select the DOM-Element from the iframeDocument:

if (!iframeDocument) {
    throw "iframe couldn't be found in DOM.";
}

var iframeContent = iframeDocument.getElementById('frameBody');

// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');

Call functions in the iframe

Get just the window element from iframe to call some global functions, variables or whole libraries (e.g. jQuery):

var iframeWindow = iframe.contentWindow;

// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');

// or
iframeContent = iframeWindow.$('#frameBody');

// or even use any other global variable
iframeWindow.myVar = window.myVar;

// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);

Note

All this is possible if you observe the same-origin policy.

How to Handle Button Click Events in jQuery?

<script type="text/javascript">

    $(document).ready(function() {

    $("#Button1").click(function() {

        alert("hello");

    });

    }
    );

</script>

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

SSRS custom number format

am assuming that you want to know how to format numbers in SSRS

Just right click the TextBox on which you want to apply formatting, go to its expression.

suppose its expression is something like below

=Fields!myField.Value

then do this

=Format(Fields!myField.Value,"##.##") 

or

=Format(Fields!myFields.Value,"00.00")

difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00

this should give you an idea.

also: you might have to convert your field into a numerical one. i.e.

  =Format(CDbl(Fields!myFields.Value),"00.00")

so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:

UPDATE :

if you want to apply variable formatting on the same column based on row values i.e. you want myField to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)

Go to the appropriate textbox and go to its expression and do this:

=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0, 
    Format(Fields!myField.Value, "##.##"),Fields!myField.Value)

so basically you are using IIF(condition, true,false) operator of SSRS, ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.

this should give you an idea, how to handle variable formatting.

Display Bootstrap Modal using javascript onClick

I was looking for the onClick option to set the title and body of the modal based on the item in a list. T145's answer helped a lot, so I wanted to share how I used it.

Make sure the tag containing the JavaScript function is of type text/javascript to avoid conflicts:

<script type="text/javascript"> function showMyModalSetTitle(myTitle, myBodyHtml) {

   /*
    * '#myModayTitle' and '#myModalBody' refer to the 'id' of the HTML tags in
    * the modal HTML code that hold the title and body respectively. These id's
    * can be named anything, just make sure they are added as necessary.
    *
    */

   $('#myModalTitle').html(myTitle);
   $('#myModalBody').html(myBodyHtml);

   $('#myModal').modal('show');
}</script>

This function can now be called in the onClick method from inside an element such as a button:

<button type="button" onClick="javascript:showMyModalSetTitle('Some Title', 'Some body txt')"> Click Me! </button>

Wait some seconds without blocking UI execution

Omar's solution is decent* if you cannot upgrade your environment to .NET 4.5 in order to gain access to the async and await APIs. That said, there here is one important change that should be made in order to avoid poor performance. A slight delay should be added between calls to Application.DoEvents() in order to prevent excessive CPU usage. By adding

Thread.Sleep(1);

before the call to Application.DoEvents(), you can add such a delay (1 millisecond) and prevent the application from using all of the cpu cycles available to it.

private void WaitNSeconds(int seconds)
{
    if (seconds < 1) return;
    DateTime _desired = DateTime.Now.AddSeconds(seconds);
    while (DateTime.Now < _desired) {
         Thread.Sleep(1);
         System.Windows.Forms.Application.DoEvents();
    }
}

*See https://blog.codinghorror.com/is-doevents-evil/ for a more detailed discussion on the potential pitfalls of using Application.DoEvents().

AngularJs $http.post() does not send data

use this way. no need to write so much

 isAuth = $http.post("Yr URL", {username: username, password: password});

and in the nodejs back end

app.post("Yr URL",function(req,resp)
{

  var username = req.body.username||req.param('username');
  var password = req.body.password||req.param('password');
}

I hope this helps

How to do sed like text replace with python?

If you really want to use a sed command without installing a new Python module, you could simply do the following:

import subprocess
subprocess.call("sed command")

need to add a class to an element

You are missing a closing h2 tag. It should be:

<h2><!-- Content --></h2> 

Quickest way to compare two generic lists for differences

This is the best solution you'll found

var list3 = list1.Where(l => list2.ToList().Contains(l));

How to parse unix timestamp to time.Time

Sharing a few functions which I created for dates:

Please note that I wanted to get time for a particular location (not just UTC time). If you want UTC time, just remove loc variable and .In(loc) function call.

func GetTimeStamp() string {
     loc, _ := time.LoadLocation("America/Los_Angeles")
     t := time.Now().In(loc)
     return t.Format("20060102150405")
}
func GetTodaysDate() string {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    current_time := time.Now().In(loc)
    return current_time.Format("2006-01-02")
}

func GetTodaysDateTime() string {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    current_time := time.Now().In(loc)
    return current_time.Format("2006-01-02 15:04:05")
}

func GetTodaysDateTimeFormatted() string {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    current_time := time.Now().In(loc)
    return current_time.Format("Jan 2, 2006 at 3:04 PM")
}

func GetTimeStampFromDate(dtformat string) string {
    form := "Jan 2, 2006 at 3:04 PM"
    t2, _ := time.Parse(form, dtformat)
    return t2.Format("20060102150405")
}

MISCONF Redis is configured to save RDB snapshots

I faced the similar issue, the main reason behind this was the memory(RAM) consumption by redis. My EC2 machine had 8GB RAM(arounf 7.4 available for consumption)

When my program was running the RAM usage went upto 7.2 GB leaving hardly ~100MB in RAM , this generally triggers the MISCONF Redis error ...

You can determine the RAM consumption using the htop command. Look for the Mem attribute after running htop command. If it shows high consumtion (like in my case it was 7.2GB/7.4GB) It's better to upgrade the instance's with larger Memory. In this scenario using config set stop-writes-on-bgsave-error no will be a disaster for the server and may result in disrupting other services running on the server(if any). So, it better to avoid the config command and UPGRADE YOUR REDIS MACHINE.

FYI: You may need to install htop to make this work : sudo apt-get install htop

One more solution to this can be some other RAM heavy service running on your system, check for other service running on your server/machine/instance and stop it if its not necessary. To check all the services running on your machine use service --status-all

And a suggestion for people directly pasting the config command , please do reasearch a bit and atleast warn the user before using such commands. And as @Rodrigo mentioned in his comment : "It does not look cool to ignore the errors."

---UPDATE---

YOu can also configure maxmemory and maxmemory-policy to define the behavior of Redis when a specific limit of memory is reached. For example, if I want to keep the memory limit of 6GB and delete the least recently used keys from the DB to make sure that redis mem usage do not exceed 6GB, then we can set these two parameters (in redis.conf or CONFIG SET command):

maxmemory 6gb
maxmemory-policy allkeys-lru

There are a lot of other values which you can set for these two parameters you can read about this from here: https://redis.io/topics/lru-cache

Returning from a void function

The first way is "more correct", what intention could there be to express? If the code ends, it ends. That's pretty clear, in my opinion.

I don't understand what could possibly be confusing and need clarification. If there's no looping construct being used, then what could possibly happen other than that the function stops executing?

I would be severly annoyed by such a pointless extra return statement at the end of a void function, since it clearly serves no purpose and just makes me feel the original programmer said "I was confused about this, and now you can be too!" which is not very nice.

Detect changed input text box

WORKING:

$("#ContentPlaceHolder1_txtNombre").keyup(function () {
    var txt = $(this).val();
        $('.column').each(function () {
            $(this).show();
            if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) == -1) {
                $(this).hide();
            }
        });
    //}
});

Form/JavaScript not working on IE 11 with error DOM7011

I had a similar problem on Internet Explorer, and got the same error number. The culprit was an HTML comment. I know it sounds unbelievable, so here is the story.

I saw a series of 6 articles on the Internet. I liked them, so I decided to download the 6 Web-Pages and store them on my Hard Drive. At the top of each page, was a couple of HTML <a> Tags, that would allow you to go to the next article or the previous article. So I changed the href attribute to point to the next folder on my Hard Drive, instead of the next URL on the Internet.

After all of the links had been re-directed, the Browser refused to display any of the Web-Pages when I clicked on the Links. The message in the Console was the Error Number that was mentioned at the top of this page.

However, the real problem was a Comment. Whenever you download a Web-Page using Google Chrome, the Chrome Browser inserts a Comment at the very top of the page that includes the URL of the location that you got the Web-Page from. After I removed the Comment at the top of each one of the 6 Pages, all of the Links worked fine ( although I continued to get the same Error Message in the Console. )

How to loop through an array containing objects and access their properties

You can use a for..of loop to loop over an array of objects.

for (let item of items) {
    console.log(item); // Will display contents of the object inside the array
}

One of the best things about for..of loops is that they can iterate over more than just arrays. You can iterate over any type of iterable, including maps and objects. Make sure you use a transpiler or something like TypeScript if you need to support older browsers.

If you wanted to iterate over a map, the syntax is largely the same as the above, except it handles both the key and value.

for (const [key, value] of items) {
  console.log(value);
}

I use for..of loops for pretty much every kind of iteration I do in Javascript. Furthermore, one of the coolest things is they also work with async/await as well.

AngularJS : Why ng-bind is better than {{}} in angular?

{{...}} is meant two-way data binding. But, ng-bind is actually meant for one-way data binding.

Using ng-bind will reduce the number of watchers in your page. Hence ng-bind will be faster than {{...}}. So, if you only want to display a value and its updates, and do not want to reflect its change from UI back to the controller, then go for ng-bind. This will increase the page performance and reduce the page load time.

<div>
  Hello, <span ng-bind="variable"></span>
</div>

Manually type in a value in a "Select" / Drop-down HTML list?

Another common solution is adding "Other.." option to the drop down and when selected show text box that is otherwise hidden. Then when submitting the form, assign hidden field value with either the drop down or textbox value and in the server side code check the hidden value.

Example: http://jsfiddle.net/c258Q/

HTML code:

Please select: <form onsubmit="FormSubmit(this);">
<input type="hidden" name="fruit" />
<select name="fruit_ddl" onchange="DropDownChanged(this);">
    <option value="apple">Apple</option>
    <option value="orange">Apricot </option>
    <option value="melon">Peach</option>
    <option value="">Other..</option>
</select> <input type="text" name="fruit_txt" style="display: none;" />
<button type="submit">Submit</button>
</form>

JavaScript:

function DropDownChanged(oDDL) {
    var oTextbox = oDDL.form.elements["fruit_txt"];
    if (oTextbox) {
        oTextbox.style.display = (oDDL.value == "") ? "" : "none";
        if (oDDL.value == "")
            oTextbox.focus();
    }
}

function FormSubmit(oForm) {
    var oHidden = oForm.elements["fruit"];
    var oDDL = oForm.elements["fruit_ddl"];
    var oTextbox = oForm.elements["fruit_txt"];
    if (oHidden && oDDL && oTextbox)
        oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;
}

And in the server side, read the value of "fruit" from the Request.

Shell command to sum integers, one per line?

Using env variable tmp

tmp=awk -v tmp="$tmp" '{print $tmp" "$1}' <filename>|echo $tmp|sed "s/ /+/g"|bc

tmp=cat <filename>|awk -v tmp="$tmp" '{print $tmp" "$1}'|echo $tmp|sed "s/ /+/g"|bc

Thanks.

What's the difference between tilde(~) and caret(^) in package.json?

Hat matching may be considered "broken" because it wont update ^0.1.2 to 0.2.0. When the software is emerging use 0.x.y versions and hat matching will only match the last varying digit (y). This is done on purpose. The reason is that while the software is evolving the API changes rapidly: one day you have these methods and the other day you have those methods and the old ones are gone. If you don't want to break the code for people who already are using your library you go and increment the major version: e.g. 1.0.0 -> 2.0.0 -> 3.0.0. So, by the time your software is finally 100% done and full-featured it will be like version 11.0.0 and that doesn't look very meaningful, and actually looks confusing. If you were, on the other hand, using 0.1.x -> 0.2.x -> 0.3.x versions then by the time the software is finally 100% done and full-featured it is released as version 1.0.0 and it means "This release is a long-term service one, you can proceed and use this version of the library in your production code, and the author won't change everything tomorrow, or next month, and he won't abandon the package".

The rule is: use 0.x.y versioning when your software hasn't yet matured and release it with incrementing the middle digit when your public API changes (therefore people having ^0.1.0 won't get 0.2.0 update and it won't break their code). Then, when the software matures, release it under 1.0.0 and increment the leftmost digit each time your public API changes (therefore people having ^1.0.0 won't get 2.0.0 update and it won't break their code).

Given a version number MAJOR.MINOR.PATCH, increment the:

MAJOR version when you make incompatible API changes,
MINOR version when you add functionality in a backwards-compatible manner, and
PATCH version when you make backwards-compatible bug fixes.

What is JavaScript garbage collection?

What is JavaScript garbage collection?

check this

What's important for a web programmer to understand about JavaScript garbage collection, in order to write better code?

In Javascript you don't care about memory allocation and deallocation. The whole problem is demanded to the Javascript interpreter. Leaks are still possible in Javascript, but they are bugs of the interpreter. If you are interested in this topic you could read more in www.memorymanagement.org

How do I remove diacritics (accents) from a string in .NET?

THIS IS THE VB VERSION (Works with GREEK) :

Imports System.Text

Imports System.Globalization

Public Function RemoveDiacritics(ByVal s As String)
    Dim normalizedString As String
    Dim stringBuilder As New StringBuilder
    normalizedString = s.Normalize(NormalizationForm.FormD)
    Dim i As Integer
    Dim c As Char
    For i = 0 To normalizedString.Length - 1
        c = normalizedString(i)
        If CharUnicodeInfo.GetUnicodeCategory(c) <> UnicodeCategory.NonSpacingMark Then
            stringBuilder.Append(c)
        End If
    Next
    Return stringBuilder.ToString()
End Function

Export result set on Dbeaver to CSV

You don't need to use the clipboard, you can export directly the whole resultset (not just what you see) to a file :

  1. Execute your query
  2. Right click any anywhere in the results
  3. click "Export resultset..." to open the export wizard
  4. Choose the format you want (CSV according to your question)
  5. Review the settings in the next panes when clicking "Next".
  6. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.


In newer versions of DBeaver you can just :

  1. right click the SQL of the query you want to export
  2. Execute > Export from query
  3. Choose the format you want (CSV according to your question)
  4. Review the settings in the next panes when clicking "Next".
  5. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.

Compared to the previous way of doing exports, this saves you step 1 (executing the query) which can be handy with time/resource intensive queries.

Why is Python running my module when I import it, and how do I stop it?

Put the code inside a function and it won't run until you call the function. You should have a main function in your main.py. with the statement:

if __name__ == '__main__':
  main()

Then, if you call python main.py the main() function will run. If you import main.py, it will not. Also, you should probably rename main.py to something else for clarity's sake.

How do I retrieve an HTML element's actual width and height?

Here is the code for WKWebView what determines a height of specific Dom element (doesn't work properly for whole page)

let html = "<body><span id=\"spanEl\" style=\"font-family: '\(taskFont.fontName)'; font-size: \(taskFont.pointSize - 4.0)pt; color: rgb(\(red), \(blue), \(green))\">\(textValue)</span></body>"
webView.navigationDelegate = self
webView.loadHTMLString(taskHTML, baseURL: nil)

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.getElementById(\"spanEl\").getBoundingClientRect().height;") { [weak self] (response, error) in
        if let nValue = response as? NSNumber {

        }
    }
}

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

Wolfram has a closed form solution for fitting an exponential. They also have similar solutions for fitting a logarithmic and power law.

I found this to work better than scipy's curve_fit. Especially when you don't have data "near zero". Here is an example:

import numpy as np
import matplotlib.pyplot as plt

# Fit the function y = A * exp(B * x) to the data
# returns (A, B)
# From: https://mathworld.wolfram.com/LeastSquaresFittingExponential.html
def fit_exp(xs, ys):
    S_x2_y = 0.0
    S_y_lny = 0.0
    S_x_y = 0.0
    S_x_y_lny = 0.0
    S_y = 0.0
    for (x,y) in zip(xs, ys):
        S_x2_y += x * x * y
        S_y_lny += y * np.log(y)
        S_x_y += x * y
        S_x_y_lny += x * y * np.log(y)
        S_y += y
    #end
    a = (S_x2_y * S_y_lny - S_x_y * S_x_y_lny) / (S_y * S_x2_y - S_x_y * S_x_y)
    b = (S_y * S_x_y_lny - S_x_y * S_y_lny) / (S_y * S_x2_y - S_x_y * S_x_y)
    return (np.exp(a), b)


xs = [33, 34, 35, 36, 37, 38, 39, 40, 41, 42]
ys = [3187, 3545, 4045, 4447, 4872, 5660, 5983, 6254, 6681, 7206]

(A, B) = fit_exp(xs, ys)

plt.figure()
plt.plot(xs, ys, 'o-', label='Raw Data')
plt.plot(xs, [A * np.exp(B *x) for x in xs], 'o-', label='Fit')

plt.title('Exponential Fit Test')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best')
plt.tight_layout()
plt.show()

enter image description here

How to set cookie in node js using express framework?

Set Cookie?

res.cookie('cookieName', 'cookieValue')

Read Cookie?

req.cookies

Demo

const express('express')
    , cookieParser = require('cookie-parser'); // in order to read cookie sent from client

app.get('/', (req,res)=>{

    // read cookies
    console.log(req.cookies) 

    let options = {
        maxAge: 1000 * 60 * 15, // would expire after 15 minutes
        httpOnly: true, // The cookie only accessible by the web server
        signed: true // Indicates if the cookie should be signed
    }

    // Set cookie
    res.cookie('cookieName', 'cookieValue', options) // options is optional
    res.send('')

})

python pip on Windows - command 'cl.exe' failed

In my case I need to install more tools from Visual Studio (I'm using VS 2017 Community and Python 3.6.4). I installed those tools (see installer screenshot here):

  1. Desktop development with C++: I included all defaulted items and the next ones:

    • Windows XP support for C++
    • Support for C++/CLI
    • VC++ 2015.3 v140 toolset
  2. Linux development with C++

Then I opened the Windows PowerShell as Administrator privilegies (Right click to open) and move folder of Visual Studio installation and find that path:

cd [Visual Studio Path]\VC\Auxiliary\Build

Then I executed this file:

.\vcvars32.bat

After that I use pip as normal, for instance, I wanted to install Mayavi:

pip install mayavi

I hope that it helps someone too.

Pipe subprocess standard output to a variable

With a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE) , you need to either use a list or use shell=True;

Either of these will work. The former is preferable.

a = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE)

a = subprocess.Popen('cdrecord --help', shell=True, stdout=subprocess.PIPE)

Also, instead of using Popen.stdout.read/Popen.stderr.read, you should use .communicate() (refer to the subprocess documentation for why).

proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()

SQL Server Management Studio, how to get execution time down to milliseconds

I don't know about expanding the information bar.

But you can get the timings set as a default for all queries showing in the "Messages" tab.

When in a Query window, go to the Query Menu item, select "query options" then select "advanced" in the "Execution" group and check the "set statistics time" / "set statistics IO" check boxes. These values will then show up in the messages area for each query without having to remember to put in the set stats on and off.

You could also use Shift + Alt + S to enable client statistics at any time

Best way to convert text files between character sets?

There is also a web tool to convert file encoding: https://webtool.cloud/change-file-encoding

It supports wide range of encodings, including some rare ones, like IBM code page 37.

How to fix the height of a <div> element?

You can try max-height: 70px; See if that works.

psql: FATAL: Ident authentication failed for user "postgres"

I had similar problem and I fixed it in pg_hba.conf when removing all ident methods even for IP6 address (in spite I have only IP4 on machine).

host all all 127.0.0.1/32 password
host all all ::1/128 password
#for pgAdmin running at local network
host all all 192.168.0.0/24 md5

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

There's a great blog post on this here:

http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/

Along with a demo here:

http://www.kylejlarson.com/files/iosdemo/

In summary, you can use the following on a div containing your main content:

.scrollable {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: scroll;
    -webkit-overflow-scrolling: touch;
}

The problem I think you're describing is when you try to scroll up within a div that is already at the top - it then scrolls up the page instead of up the div and causes a bounce effect at the top of the page. I think your question is asking how to get rid of this?

In order to fix this, the author suggests that you use ScrollFix to auto increase the height of scrollable divs.

It's also worth noting that you can use the following to prevent the user from scrolling up e.g. in a navigation element:

document.addEventListener('touchmove', function(event) {
   if(event.target.parentNode.className.indexOf('noBounce') != -1 
|| event.target.className.indexOf('noBounce') != -1 ) {
    event.preventDefault(); }
}, false);

Unfortunately there are still some issues with ScrollFix (e.g. when using form fields), but the issues list on ScrollFix is a good place to look for alternatives. Some alternative approaches are discussed in this issue.

Other alternatives, also mentioned in the blog post, are Scrollability and iScroll

Convert string to decimal, keeping fractions

decimal d = 3.00 is still 3. I guess you want to show it some where on screen or print it on log file as 3.00. You can do following

string str = d.ToString("F2");

or if you are using database to store the decimal then you can set pricision value in database.

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

Add number of days to a date

You may try this.

$i=30;
echo  date("Y-m-d",mktime(0,0,0,date('m'),date('d')+$i,date('Y')));

SQL Query - Concatenating Results into One String

If you're on SQL Server 2005 or up, you can use this FOR XML PATH & STUFF trick:

DECLARE @CodeNameString varchar(100)

SELECT 
   @CodeNameString = STUFF( (SELECT ',' + CodeName 
                             FROM dbo.AccountCodes 
                             ORDER BY Sort
                             FOR XML PATH('')), 
                            1, 1, '')

The FOR XML PATH('') basically concatenates your strings together into one, long XML result (something like ,code1,code2,code3 etc.) and the STUFF puts a "nothing" character at the first character, e.g. wipes out the "superfluous" first comma, to give you the result you're probably looking for.

UPDATE: OK - I understand the comments - if your text in the database table already contains characters like <, > or &, then my current solution will in fact encode those into &lt;, &gt;, and &amp;.

If you have a problem with that XML encoding - then yes, you must look at the solution proposed by @KM which works for those characters, too. One word of warning from me: this approach is a lot more resource and processing intensive - just so you know.

How to add buttons dynamically to my form?

First, you aren't actually creating 10 buttons. Second, you need to set the location of each button, or they will appear on top of each other. This will do the trick:

  for (int i = 0; i < 10; ++i)
  {
      var button = new Button();
      button.Location = new Point(button.Width * i + 4, 0);
      Controls.Add(button);
  }

Python: Is there an equivalent of mid, right, and left from BASIC?

slices to the rescue :)

def left(s, amount):
    return s[:amount]

def right(s, amount):
    return s[-amount:]

def mid(s, offset, amount):
    return s[offset:offset+amount]

Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

You either need to increase the max_connections configuration setting or (probably better) use connection pooling to route a large number of user requests through a smaller connection pool.

https://wiki.postgresql.org/wiki/Number_Of_Database_Connections

What is a "web service" in plain English?

A web service, as used by software developers, generally refers to an operation that is performed on a remote server and invoked using the XML/SOAP specification. As with all definitions, there are nuances to it, but that's the most common use of the term.

history.replaceState() example?

Here is a minimal, contrived example.

console.log( window.location.href );  // whatever your current location href is
window.history.replaceState( {} , 'foo', '/foo' );
console.log( window.location.href );  // oh, hey, it replaced the path with /foo

There is more to replaceState() but I don't know what exactly it is that you want to do with it.

Excel Reference To Current Cell

Several years too late:

Just for completeness I want to give yet another answer:

First, go to Excel-Options -> Formulas and enable R1C1 references. Then use

  =CELL("width", RC)

RC always refers the current Row, current Column, i.e. "this cell".

Rick Teachey's solution is basically a tweak to make the same possible in A1 reference style (see also GSerg's comment to Joey's answer and note his comment to Patrick McDonald's answer).

Cheers
:-)

Date vs DateTime

You can return DateTime where the time portion is 00:00:00 and just ignore it. The dates are handled as timestamp integers so it makes sense to combine the date with the time as that is present in the integer anyway.

How to discard local commits in Git?

I have seen instances where the remote became out of sync and needed to be updated. If a reset --hard or a branch -D fail to work, try

git pull origin
git reset --hard 

send mail from linux terminal in one line

You can install the mail package in Ubuntu with below command.

For Ubuntu -:

$ sudo apt-get install -y mailutils

For CentOs-:

$ sudo yum install -y mailx

Test Mail command-:

$ echo "Mail test" | mail -s "Subject" [email protected]

How to unpack pkl file?

The pickle (and gzip if the file is compressed) module need to be used

NOTE: These are already in the standard Python library. No need to install anything new

How to get a variable name as a string in PHP?

This is the way I did it

function getVar(&$var) {
    $tmp = $var; // store the variable value
    $var = '_$_%&33xc$%^*7_r4'; // give the variable a new unique value
    $name = array_search($var, $GLOBALS); // search $GLOBALS for that unique value and return the key(variable)
    $var = $tmp; // restore the variable old value
    return $name;
}

Usage

$city  = "San Francisco";
echo getVar($city); // city

Note: some PHP 7 versions will not work properly due to a bug in array_search with $GLOBALS, however all other versions will work.

See this https://3v4l.org/UMW7V

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

I was having the same issue when accessing a published ASP.NET Web Api. In my case, I realized that when I was about to publish the Web Api, I had not indicated a connection string inside the Databases section:

After using the three dot button, the connection string will be displayed on the text field to the left

So I generated it using the three dot button, and after publishing, it worked.

What is weird, is that for a long time I am pretty sure that there was no connection string in that configuration but it still worked.

Pandas: how to change all the values of a column?

Or if one want to use lambda function in the apply function:

data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))

Get list from pandas DataFrame column headers

It's interesting but df.columns.values.tolist() is almost 3 times faster then df.columns.tolist() but I thought that they are the same:

In [97]: %timeit df.columns.values.tolist()
100000 loops, best of 3: 2.97 µs per loop

In [98]: %timeit df.columns.tolist()
10000 loops, best of 3: 9.67 µs per loop

Class not registered Error

For me, I had to install Microsoft Access Database Engine 2010 Redistributable and restart my computer.

Vagrant ssh authentication failure

Between all of the responses here, there are lots of good things to try. For completeness, if you

ssh vagrant@localhost -p 2222

as @Bizmate suggests, and it fails, be sure you have

AllowUsers vagrant

in the /etc/ssh/sshd_config of your guest/vagrant machine.

How to install PostgreSQL's pg gem on Ubuntu?

For anyone who is still having issues after trying all the answers on this page, the following (finally) worked:

sudo apt-get install libgmp3-dev
gem install pg

This was after doing everything else mentioned on this page.

postgresql 9.5.8
Ubuntu 16.10

How to inflate one view with a layout

Even simpler way is to use

View child = View.inflate(context, R.layout.child, null)
item.addChild(child) //attach to your item

Get page title with Selenium WebDriver using Java

If you're using Selenium 2.0 / Webdriver you can call driver.getTitle() or driver.getPageSource() if you want to search through the actual page source.

How to access site running apache server over lan without internet connection

In your httpd.conf make sure you have:

Listen *:80

And if you are using VirtualHosts then set them as given below:

NameVirtualHost *
<VirtualHost *>
   ...
</VirtualHost>

MySQL DELETE FROM with subquery as condition

You need to refer to the alias again in the delete statement, like:

DELETE th FROM term_hierarchy AS th
....

As outlined here in MySQL docs.

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

The only thing that worked for me in this situation was the self-created openssl.cnf file.

Here are the basics needed for this exercise (edit as needed):

#
# OpenSSL configuration file.
#

# Establish working directory.

dir                         = .

[ ca ]
default_ca                  = CA_default

[ CA_default ]
serial                      = $dir/serial
database                    = $dir/certindex.txt
new_certs_dir               = $dir/certs
certificate                 = $dir/cacert.pem
private_key                 = $dir/private/cakey.pem
default_days                = 365
default_md                  = md5
preserve                    = no
email_in_dn                 = no
nameopt                     = default_ca
certopt                     = default_ca
policy                      = policy_match

[ policy_match ]
countryName                 = match
stateOrProvinceName         = match
organizationName            = match
organizationalUnitName      = optional
commonName                  = supplied
emailAddress                = optional

[ req ]
default_bits                = 1024          # Size of keys
default_keyfile             = key.pem       # name of generated keys
default_md                  = md5               # message digest algorithm
string_mask                 = nombstr       # permitted characters
distinguished_name          = req_distinguished_name
req_extensions              = v3_req

[ req_distinguished_name ]
# Variable name             Prompt string
#-------------------------    ----------------------------------
0.organizationName          = Organization Name (company)
organizationalUnitName      = Organizational Unit Name (department, division)
emailAddress                = Email Address
emailAddress_max            = 40
localityName                = Locality Name (city, district)
stateOrProvinceName         = State or Province Name (full name)
countryName                 = Country Name (2 letter code)
countryName_min             = 2
countryName_max             = 2
commonName                  = Common Name (hostname, IP, or your name)
commonName_max              = 64

# Default values for the above, for consistency and less typing.
# Variable name             Value
#------------------------     ------------------------------
0.organizationName_default  = My Company
localityName_default        = My Town
stateOrProvinceName_default = State or Providence
countryName_default         = US

[ v3_ca ]
basicConstraints            = CA:TRUE
subjectKeyIdentifier        = hash
authorityKeyIdentifier      = keyid:always,issuer:always

[ v3_req ]
basicConstraints            = CA:FALSE
subjectKeyIdentifier        = hash

I hope that helps.

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

An ideal solution will:

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

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

HTML

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

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

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

CSS

nav {
  width: 900px;
}

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

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

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

How do I resolve "Run-time error '429': ActiveX component can't create object"?

The file msrdo20.dll is missing from the installation.

According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.

I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:

regsvr32 c:\windows\system32\msrdo20.dll

In an ideal world you would package this up with the redistributable.

JavaScript array to CSV

The cited answer was wrong. You had to change

csvContent += index < infoArray.length ? dataString+ "\n" : dataString;

to

csvContent += dataString + "\n";

As to why the cited answer was wrong (funny it has been accepted!): index, the second parameter of the forEach callback function, is the index in the looped-upon array, and it makes no sense to compare this to the size of infoArray, which is an item of said array (which happens to be an array too).

EDIT

Six years have passed now since I wrote this answer. Many things have changed, including browsers. The following was part of the answer:

START of aged part

BTW, the cited code is suboptimal. You should avoid to repeatedly append to a string. You should append to an array instead, and do an array.join("\n") at the end. Like this:

var lineArray = [];
data.forEach(function (infoArray, index) {
    var line = infoArray.join(",");
    lineArray.push(index == 0 ? "data:text/csv;charset=utf-8," + line : line);
});
var csvContent = lineArray.join("\n");

END of aged part

(Keep in mind that the CSV case is a bit different from generic string concatenation, since for every string you also have to add the separator.)

Anyway, the above seems not to be true anymore, at least not for Chrome and Firefox (it seems to still be true for Safari, though).

To put an end to uncertainty, I wrote a jsPerf test that tests whether, in order to concatenate strings in a comma-separated way, it's faster to push them onto an array and join the array, or to concatenate them first with the comma, and then directly with the result string using the += operator.

Please follow the link and run the test, so that we have enough data to be able to talk about facts instead of opinions.

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

Correlation heatmap

  1. Use the 'jet' colormap for a transition between blue and red.
  2. Use pcolor() with the vmin, vmax parameters.

It is detailed in this answer: https://stackoverflow.com/a/3376734/21974

How to change DatePicker dialog color for Android 5.0

The reason why Neil's suggestion results in a fullscreen DatePicker is the choice of parent theme:

<!-- Theme.AppCompat.Light is not a dialog theme -->
<style name="DialogTheme" parent="**Theme.AppCompat.Light**">
    <item name="colorAccent">@color/blue_500</item>
</style>

Moreover, if you go this route, you have to specify the theme while creating the DatePickerDialog:

// R.style.DialogTheme
new DatePickerDialog(MainActivity.this, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        //DO SOMETHING
    }
}, 2015, 02, 26).show();

This, in my opinion, is not good. One should try to keep the styling out of java and inside styles.xml/themes.xml.

I do agree that Neil's suggestion, with a bit of change (changing the parent theme to say, Theme.Material.Light.Dialog) will get you the desired result. But, here's the other way:

On first inspection, we come across datePickerStyle which defines things such as: headerBackground(what you are trying to change), dayOfWeekBackground, and a few other text-colors and text-styles.

Overriding this attribute in your app's theme will not work. DatePickerDialog uses a separate theme assignable by the attribute datePickerDialogTheme. So, for our changes to take affect, we must override datePickerStyle inside an overriden datePickerDialogTheme.

Here we go:

Override datePickerDialogTheme inside your app's base theme:

<style name="AppBaseTheme" parent="android:Theme.Material.Light">
    ....
    <item name="android:datePickerDialogTheme">@style/MyDatePickerDialogTheme</item>
</style>

Define MyDatePickerDialogTheme. The choice of parent theme will depend on what your app's base theme is: it could be either Theme.Material.Dialog or Theme.Material.Light.Dialog:

<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
    <item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
</style>

We have overridden datePickerStyle with the style MyDatePickerStyle. The choice of parent will once again depend on what your app's base theme is: either Widget.Material.DatePicker or Widget.Material.Light.DatePicker. Define it as per your requirements:

<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
    <item name="android:headerBackground">@color/chosen_header_bg_color</item>
</style>

Currently, we are only overriding headerBackground which by default is set to ?attr/colorAccent (this is also why Neil suggestion works in changing the background). But there's quite a lot of customization possible:

dayOfWeekBackground
dayOfWeekTextAppearance
headerMonthTextAppearance
headerDayOfMonthTextAppearance
headerYearTextAppearance
headerSelectedTextColor
yearListItemTextAppearance
yearListSelectorColor
calendarTextColor
calendarSelectedTextColor

If you don't want this much control (customization), you don't need to override datePickerStyle. colorAccent controls most of the DatePicker's colors. So, overriding just colorAccent inside MyDatePickerDialogTheme should work:

<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
    <item name="android:colorAccent">@color/date_picker_accent</item>

    <!-- No need to override 'datePickerStyle' -->
    <!-- <item name="android:datePickerStyle">@style/MyDatePickerStyle</item> -->
</style>

Overriding colorAccent gives you the added benefit of changing OK & CANCEL text colors as well. Not bad.

This way you don't have to provide any styling information to DatePickerDialog's constructor. Everything has been wired properly:

DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

    }
 }, 2015, 5, 22);

 dpd.show();

Running PHP script from the command line

On SuSE, there are two different configuration files for PHP: one for Apache, and one for CLI (command line interface). In the /etc/php5/ directory, you will find an "apache2" directory and a "cli" directory. Each has a "php.ini" file. The files are for the same purpose (php configuration), but apply to the two different ways of running PHP. These files, among other things, load the modules PHP uses.

If your OS is similar, then these two files are probably not the same. Your Apache php.ini is probably loading the gearman module, while the cli php.ini isn't. When the module was installed (auto or manual), it probably only updated the Apache php.ini file.

You could simply copy the Apache php.ini file over into the cli directory to make the CLI environment exactly like the Apache environment.

Or, you could find the line that loads the gearman module in the Apache file and copy/paste just it to the CLI file.

How can I round a number in JavaScript? .toFixed() returns a string?

May be too late to answer but you can multiple the output with 1 to convert to number again, here is an example.

_x000D_
_x000D_
const x1 = 1211.1212121;
const x2 = x1.toFixed(2)*1;
console.log(typeof(x2));
_x000D_
_x000D_
_x000D_

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

For swift

var dateString:String = "2014-05-20";
var dateFmt = NSDateFormatter()
// the format you want
dateFmt.dateFormat = "yyyy-MM-dd"
var date1:NSDate = dateFmt.dateFromString(dateString)!;

How do I wait for a promise to finish before returning the variable of a function?

You're not actually using promises here. Parse lets you use callbacks or promises; your choice.

To use promises, do the following:

query.find().then(function() {
    console.log("success!");
}, function() {
    console.log("error");
});

Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then() call. So far this would be exactly the same as regular callbacks.

To actually make good use of promises is when you chain them, like this:

query.find().then(function() {
    console.log("success!");

    return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
    console.log("error");
}).then(function() {
    console.log("success on second callback!");
}, function() {
    console.log("error on second callback");
});

Does GPS require Internet?

As others have said, you do not need internet for GPS.

GPS is basically a satellite based positioning system that is designed to calculate geographic coordinates based on timing information received from multiple satellites in the GPS constellation. GPS has a relatively slow time to first fix (TTFF), and from a cold start (meaning without a last known position), it can take up to 15 minutes to download the data it needs from the satellites to calculate a position. A-GPS used by cellular networks shortens this time by using the cellular network to deliver the satellite data to the phone.

But regardless of whether it is an A-GPS or GPS location, all that is derived is Geographic Coordinates (latitude/longitude). It is impossible to obtain more from GPS only.

To be able to return anything other than coordinates (such as an address), you need some mechanism to do Reverse Geocoding. Typically this is done by querying a server or a web service (like using Google Maps or Bing Maps, but there are others). Some of the services will allow you to cache data locally, but it would still require an internet connection for periods of time to download the map information in the surrounding area.

While it requires a significant amount of effort, you can write your own tool to do the reverse geocoding, but you still need to be able to house the data somewhere as the amount of data required to do this is far more you can store on a phone, which means you still need an internet connection to do it. If you think of tools like Garmin GPS Navigation units, they do store the data locally, so it is possible, but you will need to optimize it for maximum storage and would probably need more than is generally available in a phone.

Bottom line:

The short answer to your question is, no you do not need an active internet connection to get coordinates, but unless you are building a specialized device or have unlimited storage, you will need an internet connection to turn those coordinates into anything else.

SyntaxError: Cannot use import statement outside a module

Verify that you have the latest version of Node installed (or, at least 13.2.0+). Then do one of the following, as described in the documentation:

Option 1

In the nearest parent package.json file, add the top-level "type" field with a value of "module". This will ensure that all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.

// package.json
{
  "type": "module"
}

Option 2

Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.

Calling a function of a module by using its name (a string)

The answer (I hope) no one ever wanted

Eval like behavior

getattr(locals().get("foo") or globals().get("foo"), "bar")()

Why not add auto-importing

getattr(
    locals().get("foo") or 
    globals().get("foo") or
    __import__("foo"), 
"bar")()

In case we have extra dictionaries we want to check

getattr(next((x for x in (f("foo") for f in 
                          [locals().get, globals().get, 
                           self.__dict__.get, __import__]) 
              if x)),
"bar")()

We need to go deeper

getattr(next((x for x in (f("foo") for f in 
              ([locals().get, globals().get, self.__dict__.get] +
               [d.get for d in (list(dd.values()) for dd in 
                                [locals(),globals(),self.__dict__]
                                if isinstance(dd,dict))
                if isinstance(d,dict)] + 
               [__import__])) 
        if x)),
"bar")()

RegEx to extract all matches from string using RegExp.exec

If you're able to use matchAll here's a trick:

Array.From has a 'selector' parameter so instead of ending up with an array of awkward 'match' results you can project it to what you really need:

Array.from(str.matchAll(regexp), m => m[0]);

If you have named groups eg. (/(?<firstname>[a-z][A-Z]+)/g) you could do this:

Array.from(str.matchAll(regexp), m => m.groups.firstName);

CSS3 transform: rotate; in IE9

Try this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
    margin-left: 50px;
    margin-top: 50px;
    margin-right: 50px;
    margin-bottom: 50px;
}
.rotate {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -sand-transform: rotate(10deg);
    display: block;
    position: fixed;
}
</style>
</head>

<body>
<div class="rotate">Alpesh</div>
</body>
</html>

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

HP computer method:

Make sure your BIOS is updated before changing the settings. If you have an HP computer, they have an HP Support Assistant app you can configure to automatically install BIOS updates. Then follow the instructions on how to update BIOS.

Then you can look up which HP computer for how to change the BIOS in a search engine.

For an HP ZBook, follow these steps:

  1. Restart your computer with the shift key pressed (before you click restart) until a menu appears.
  2. Choose BIOS Setup on the screen (or press F10).
  3. Click on Troubleshoot.
  4. Using your arrow keys in this menu, go to Advanced Options.
  5. Select UEFI Firmware Settings.
  6. Select restart.
  7. It reboots into a Startup menu
  8. Choose BIOS Setup With arrow keys go to Advanced tab.
  9. Choose the System Options.
  10. Check both the Virtualization Technology (VTx) and the Virtualization Technology for Directed I/O (VTd) boxes.
  11. Go back to the Main tab and at bottom choose Save and Exit.
  12. Computer will restart.

How to create a HashMap with two keys (Key-Pair, Value)?

When you create your own key pair object, you should face a few thing.

First, you should be aware of implementing hashCode() and equals(). You will need to do this.

Second, when implementing hashCode(), make sure you understand how it works. The given user example

public int hashCode() {
    return this.x ^ this.y;
}

is actually one of the worst implementations you can do. The reason is simple: you have a lot of equal hashes! And the hashCode() should return int values that tend to be rare, unique at it's best. Use something like this:

public int hashCode() {
  return (X << 16) + Y;
}

This is fast and returns unique hashes for keys between -2^16 and 2^16-1 (-65536 to 65535). This fits in almost any case. Very rarely you are out of this bounds.

Third, when implementing equals() also know what it is used for and be aware of how you create your keys, since they are objects. Often you do unnecessary if statements cause you will always have the same result.

If you create keys like this: map.put(new Key(x,y),V); you will never compare the references of your keys. Cause everytime you want to acces the map, you will do something like map.get(new Key(x,y));. Therefore your equals() does not need a statement like if (this == obj). It will never occure.

Instead of if (getClass() != obj.getClass()) in your equals() better use if (!(obj instanceof this)). It will be valid even for subclasses.

So the only thing you need to compare is actually X and Y. So the best equals() implementation in this case would be:

public boolean equals (final Object O) {
  if (!(O instanceof Key)) return false;
  if (((Key) O).X != X) return false;
  if (((Key) O).Y != Y) return false;
  return true;
}

So in the end your key class is like this:

public class Key {

  public final int X;
  public final int Y;

  public Key(final int X, final int Y) {
    this.X = X;
    this.Y = Y;
  }

  public boolean equals (final Object O) {
    if (!(O instanceof Key)) return false;
    if (((Key) O).X != X) return false;
    if (((Key) O).Y != Y) return false;
    return true;
  }

  public int hashCode() {
    return (X << 16) + Y;
  }

}

You can give your dimension indices X and Y a public access level, due to the fact they are final and do not contain sensitive information. I'm not a 100% sure whether private access level works correctly in any case when casting the Object to a Key.

If you wonder about the finals, I declare anything as final which value is set on instancing and never changes - and therefore is an object constant.

Aligning a button to the center

For me it worked using flexbox, which is in my opinion the cleanest solution.

Add a css class around the parent div / element with :

.parent {
display: flex;
}

and for the button use:

.button {
justify-content: center;
}

You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.

If this is not working, try :

#wrapper {
    display:flex;
    justify-content: center;
}

How do I use LINQ Contains(string[]) instead of Contains(string)

string[] stringArray = {1,45,20,10};
from xx in table 
where stringArray.Contains(xx.uid.ToString()) 
select xx

How to get JSON object from Razor Model object in javascript

In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent so you don't need to wrap it with a call to Html.Raw().

It should be as simple as:

<script>
  var json = @Json.Serialize(Model.CollegeInformationlist);
</script>

Error message: "'chromedriver' executable needs to be available in the path"

When I downloaded chromedriver.exe I just move it in PATH folder C:\Windows\System32\chromedriver.exe and had exact same problem.

For me solution was to just change folder in PATH, so I just moved it at Pycharm Community bin folder that was also in PATH. ex:

  • C:\Windows\System32\chromedriver.exe --> Gave me exception
  • C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.3\bin\chromedriver.exe --> worked fine

Applying .gitignore to committed files

Follow these steps:

  1. Add path to gitignore file

  2. Run this command

    git rm -r --cached foldername
    
  3. commit changes as usually.

How can I return two values from a function in Python?

And this is an alternative.If you are returning as list then it is simple to get the values.

def select_choice():
    ...
    return [i, card]

values = select_choice()

print values[0]
print values[1]

JavaScript listener, "keypress" doesn't detect backspace?

My numeric control:

function CheckNumeric(event) {
    var _key = (window.Event) ? event.which : event.keyCode;
    if (_key > 95 && _key < 106) {
        return true;
    }
    else if (_key > 47 && _key < 58) {
        return true;
    }
    else {
        return false;
    }
}

<input type="text" onkeydown="return CheckNumerick(event);" />

try it

BackSpace key code is 8

Make div stay at bottom of page's content all the time even when there are scrollbars

Unfortunately you can't do this with out adding a little extra HTML and having one piece of CSS rely on another.

HTML

First you need to wrap your header,footer and #body into a #holder div:

<div id="holder">
    <header>.....</header>
    <div id="body">....</div>
    <footer>....</footer>
</div>

CSS

Then set height: 100% to html and body (actual body, not your #body div) to ensure you can set minimum height as a percentage on child elements.

Now set min-height: 100% on the #holder div so it fills the content of the screen and use position: absolute to sit the footer at the bottom of the #holder div.

Unfortunately, you have to apply padding-bottom to the #body div that is the same height as the footer to ensure that the footer does not sit above any content:

html,body{
    height: 100%
}

#holder{
    min-height: 100%;
    position:relative;
}

#body{
    padding-bottom: 100px;    /* height of footer */
}

footer{
    height: 100px; 
    width:100%;
    position: absolute;
    left: 0;
    bottom: 0; 
}

Working example, short body: http://jsfiddle.net/ELUGc/

Working example, long body: http://jsfiddle.net/ELUGc/1/

Sequence contains no matching element

Maybe using Where() before First() can help you, as my problem has been solved in this case.

var documentRow = _dsACL.Documents.Where(o => o.ID == id).FirstOrDefault();

How does delete[] know it's an array?

The answer:

int* pArray = new int[5];

int size = *(pArray-1);

Posted above is not correct and produces invalid value. The "-1"counts elements On 64 bit Windows OS the correct buffer size resides in Ptr - 4 bytes address

Why do I get "'property cannot be assigned" when sending an SMTP email?

Finally got working :)

using System.Net.Mail;
using System.Text;

...

// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("[email protected]","password");

MailMessage mm = new MailMessage("[email protected]", "[email protected]", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

client.Send(mm);

sorry about poor spelling before

How do I configure git to ignore some files locally?

You can simply add a .gitignore file to your home directory, i.e. $HOME/.gitignore or ~/.gitignore. Then tell git to use that file with the command:

git config --global core.excludesfile ~/.gitignore

This is a normal .gitignore file which git references when deciding what to ignore. Since it's in your home directory, it applies only to you and doesn't pollute any project .gitignore files.

I've been using this approach for years with great results.

How to find what code is run by a button or element in Chrome using Developer Tools

Alexander Pavlov's answer gets the closest to what you want.

Due to the extensiveness of jQuery's abstraction and functionality, a lot of hoops have to be jumped in order to get to the meat of the event. I have set up this jsFiddle to demonstrate the work.


1. Setting up the Event Listener Breakpoint

You were close on this one.

  1. Open the Chrome Dev Tools (F12), and go to the Sources tab.
  2. Drill down to Mouse -> Click
    Chrome Dev Tools -> Sources tab -> Mouse -> Click
    (click to zoom)

2. Click the button!

Chrome Dev Tools will pause script execution, and present you with this beautiful entanglement of minified code:

Chrome Dev Tools paused script execution (click to zoom)


3. Find the glorious code!

Now, the trick here is to not get carried away pressing the key, and keep an eye out on the screen.

  1. Press the F11 key (Step In) until desired source code appears
  2. Source code finally reached
    • In the jsFiddle sample provided above, I had to press F11 108 times before reaching the desired event handler/function
    • Your mileage may vary, depending on the version of jQuery (or framework library) used to bind the events
    • With enough dedication and time, you can find any event handler/function

Desired event handler/function


4. Explanation

I don't have the exact answer, or explanation as to why jQuery goes through the many layers of abstractions it does - all I can suggest is that it is because of the job it does to abstract away its usage from the browser executing the code.

Here is a jsFiddle with a debug version of jQuery (i.e., not minified). When you look at the code on the first (non-minified) breakpoint, you can see that the code is handling many things:

    // ...snip...

    if ( !(eventHandle = elemData.handle) ) {
        eventHandle = elemData.handle = function( e ) {
            // Discard the second event of a jQuery.event.trigger() and
            // when an event is called after a page has unloaded
            return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
                jQuery.event.dispatch.apply( elem, arguments ) : undefined;
        };
    }

    // ...snip...

The reason I think you missed it on your attempt when the "execution pauses and I jump line by line", is because you may have used the "Step Over" function, instead of Step In. Here is a StackOverflow answer explaining the differences.

Finally, the reason why your function is not directly bound to the click event handler is because jQuery returns a function that gets bound. jQuery's function in turn goes through some abstraction layers and checks, and somewhere in there, it executes your function.

How to fix Cannot find module 'typescript' in Angular 4?

If you have cloned your project from git or somewhere then first, you should type npm install.

How do I set the background color of my main screen in Flutter?

There are many ways of doing it, I am listing few here.

  1. Using backgroundColor

    Scaffold(
      backgroundColor: Colors.black,
      body: Center(...),
    )
    
  2. Using Container in SizedBox.expand

    Scaffold(
      body: SizedBox.expand(
        child: Container(
          color: Colors.black,
          child: Center(...)
        ),
      ),
    )
    
  3. Using Theme

    Theme(
      data: Theme.of(context).copyWith(scaffoldBackgroundColor: Colors.black),
      child: Scaffold(
        body: Center(...),
      ),
    )
    

Need to get current timestamp in Java

Print a Timestamp in java, using the java.sql.Timestamp.

import java.sql.Timestamp;
import java.util.Date;

public class GetCurrentTimeStamp {
    public static void main( String[] args ){
        java.util.Date date= new java.util.Date();
        System.out.println(new Timestamp(date.getTime()));
    }
}

This prints:

2014-08-07 17:34:16.664

Print a Timestamp in Java using SimpleDateFormat on a one-liner.

import java.util.Date;
import java.text.SimpleDateFormat;

class Runner{
    public static void main(String[] args){

        System.out.println(
            new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date()));

    }

}

Prints:

08/14/2014 14:10:38

Java date format legend:

G Era designation      Text               AD
y Year                 Year               1996; 96
M Month in year        Month              July; Jul; 07
w Week in year         Number             27
W Week in month        Number             2
D Day in year          Number             189
d Day in month         Number             10
F Day of week in month Number             2
E Day in week          Text               Tuesday; Tue
a Am/pm marker         Text               PM
H Hour in day (0-23)   Number             0
k Hour in day (1-24)   Number             24
K Hour in am/pm (0-11) Number             0
h Hour in am/pm (1-12) Number             12
m Minute in hour       Number             30
s Second in minute     Number             55
S Millisecond          Number             978
z Time zone            General time zone  Pacific Standard Time; PST; GMT-08:00
Z Time zone            RFC 822 time zone  -0800

Javascript call() & apply() vs bind()?

It allows to set the value for this independent of how the function is called. This is very useful when working with callbacks:

  function sayHello(){
    alert(this.message);
  }

  var obj = {
     message : "hello"
  };
  setTimeout(sayHello.bind(obj), 1000);

To achieve the same result with call would look like this:

  function sayHello(){
    alert(this.message);
  }

  var obj = {
     message : "hello"
  };
  setTimeout(function(){sayHello.call(obj)}, 1000);

Why are exclamation marks used in Ruby methods?

In general, methods that end in ! indicate that the method will modify the object it's called on. Ruby calls these as "dangerous methods" because they change state that someone else might have a reference to. Here's a simple example for strings:

foo = "A STRING"  # a string called foo
foo.downcase!     # modifies foo itself
puts foo          # prints modified foo

This will output:

a string

In the standard libraries, there are a lot of places you'll see pairs of similarly named methods, one with the ! and one without. The ones without are called "safe methods", and they return a copy of the original with changes applied to the copy, with the callee unchanged. Here's the same example without the !:

foo = "A STRING"    # a string called foo
bar = foo.downcase  # doesn't modify foo; returns a modified string
puts foo            # prints unchanged foo
puts bar            # prints newly created bar

This outputs:

A STRING
a string

Keep in mind this is just a convention, but a lot of Ruby classes follow it. It also helps you keep track of what's getting modified in your code.

What's the difference between Unicode and UTF-8?

most editors support save as ‘Unicode’ encoding actually.

This is an unfortunate misnaming perpetrated by Windows.

Because Windows uses UTF-16LE encoding internally as the memory storage format for Unicode strings, it considers this to be the natural encoding of Unicode text. In the Windows world, there are ANSI strings (the system codepage on the current machine, subject to total unportability) and there are Unicode strings (stored internally as UTF-16LE).

This was all devised in the early days of Unicode, before we realised that UCS-2 wasn't enough, and before UTF-8 was invented. This is why Windows's support for UTF-8 is all-round poor.

This misguided naming scheme became part of the user interface. A text editor that uses Windows's encoding support to provide a range of encodings will automatically and inappropriately describe UTF-16LE as “Unicode”, and UTF-16BE, if provided, as “Unicode big-endian”.

(Other editors that do encodings themselves, like Notepad++, don't have this problem.)

If it makes you feel any better about it, ‘ANSI’ strings aren't based on any ANSI standard, either.

Read a variable in bash with a default value

You can use parameter expansion, e.g.

read -p "Enter your name [Richard]: " name
name=${name:-Richard}
echo $name

Including the default value in the prompt between brackets is a fairly common convention

What does the :-Richard part do? From the bash manual:

${parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

Also worth noting that...

In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

So if you use webpath=${webpath:-~/httpdocs} you will get a result of /home/user/expanded/path/httpdocs not ~/httpdocs, etc.

How to change the background color of the options menu?

If you want to set an arbitrary color, this seem to work rather well for androidx. Tested on KitKat and Pie. Put this into your AppCompatActivity:

@Override public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
    if (name.equals("androidx.appcompat.view.menu.ListMenuItemView") &&
            parent.getParent() instanceof FrameLayout) {
            ((View) parent.getParent()).setBackgroundColor(yourFancyColor);
    }
    return super.onCreateView(parent, name, context, attrs);
}

This sets the color of android.widget.PopupWindow$PopupBackgroundView, which, as you might have guessed, draws the background color. There's no overdraw and you can use semi-transparent colors as well.

jquery, find next element by class

In this case you need to go up to the <tr> then use .next(), like this:

$(obj).closest('tr').next().find('.class');

Or if there may be rows in-between without the .class inside, you can use .nextAll(), like this:

$(obj).closest('tr').nextAll(':has(.class):first').find('.class');

Is the practice of returning a C++ reference variable evil?

I ran into a real problem where it was indeed evil. Essentially a developer returned a reference to an object in a vector. That was Bad!!!

The full details I wrote about in Janurary: http://developer-resource.blogspot.com/2009/01/pros-and-cons-of-returing-references.html

Remove large .pack file created by git

Scenario A: If your large files were only added to a branch, you don't need to run git filter-branch. You just need to delete the branch and run garbage collection:

git branch -D mybranch
git reflog expire --expire-unreachable=all --all
git gc --prune=all

Scenario B: However, it looks like based on your bash history, that you did merge the changes into master. If you haven't shared the changes with anyone (no git push yet). The easiest thing would be to reset master back to before the merge with the branch that had the big files. This will eliminate all commits from your branch and all commits made to master after the merge. So you might lose changes -- in addition to the big files -- that you may have actually wanted:

git checkout master
git log # Find the commit hash just before the merge
git reset --hard <commit hash>

Then run the steps from the scenario A.

Scenario C: If there were other changes from the branch or changes on master after the merge that you want to keep, it would be best to rebase master and selectively include commits that you want:

git checkout master
git log # Find the commit hash just before the merge
git rebase -i <commit hash>

In your editor, remove lines that correspond to the commits that added the large files, but leave everything else as is. Save and quit. Your master branch should only contain what you want, and no large files. Note that git rebase without -p will eliminate merge commits, so you'll be left with a linear history for master after <commit hash>. This is probably okay for you, but if not, you could try with -p, but git help rebase says combining -p with the -i option explicitly is generally not a good idea unless you know what you are doing.

Then run the commands from scenario A.

How to run PowerShell in CMD

Try just:

powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

Is there any way to start with a POST request using Selenium?

Selenium doesn't currently offer API for this, but there are several ways to initiate an HTTP request in your test. It just depends what language you are writing in.

In Java for example, it might look like this:

// setup the request
String request = "startpoint?stuff1=foo&stuff2=bar";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");

// get a response - maybe "success" or "true", XML or JSON etc.
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
    response.append(line);
    response.append('\r');
}
bufferedReader.close();

// continue with test
if (response.toString().equals("expected response"){
    // do selenium
}

How to read and write excel file

You can also consider JExcelApi. I find it better designed than POI. There's a tutorial here.

How do I know which version of Javascript I'm using?

JavaScript 1.2 was introduced with Netscape Navigator 4 in 1997. That version number only ever had significance for Netscape browsers. For example, Microsoft's implementation (as used in Internet Explorer) is called JScript, and has its own version numbering which bears no relation to Netscape's numbering.

Can I make 'git diff' only the line numbers AND changed file names?

So easy:

git diff --name-only

Go forth and diff!

Remove sensitive files and their commits from Git history

I've had to do this a few times to-date. Note that this only works on 1 file at a time.

  1. Get a list of all commits that modified a file. The one at the bottom will the the first commit:

    git log --pretty=oneline --branches -- pathToFile

  2. To remove the file from history use the first commit sha1 and the path to file from the previous command, and fill them into this command:

    git filter-branch --index-filter 'git rm --cached --ignore-unmatch <path-to-file>' -- <sha1-where-the-file-was-first-added>..

Passing ArrayList through Intent

I have done this one by Passing ArrayList in form of String.

  1. Add compile 'com.google.code.gson:gson:2.2.4' in dependencies block build.gradle.

  2. Click on Sync Project with Gradle Files

Cars.java:

public class Cars {
    public String id, name;
}

FirstActivity.java

When you want to pass ArrayList:

List<Cars> cars= new ArrayList<Cars>();
cars.add(getCarModel("1", "A"));
cars.add(getCarModel("2", "B"));
cars.add(getCarModel("3", "C"));
cars.add(getCarModel("4", "D"));

Gson gson = new Gson();

String jsonCars = gson.toJson(cars);

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("list_as_string", jsonCars);
startActivity(intent);

Get CarsModel by Function:

private Cars getCarModel(String id, String name){
       Cars cars = new Cars();
       cars.id = id;
       cars.name = name;
    return cars;
 }

SecondActivity.java

You have to import java.lang.reflect.Type ;

on onCreate() to retrieve ArrayList:

String carListAsString = getIntent().getStringExtra("list_as_string");

Gson gson = new Gson();
Type type = new TypeToken<List<Cars>>(){}.getType();
List<Cars> carsList = gson.fromJson(carListAsString, type);
for (Cars cars : carsList){
   Log.i("Car Data", cars.id+"-"+cars.name);
}

Hope this will save time, I saved it.

Done

Notepad++ - How can I replace blank lines

This will remove any number of blank lines

CTRL + H to replace

Select Extended search mode

replace all \r\n with (space)

then switch to regular expression and replace all \s+ with \n

What is <scope> under <dependency> in pom.xml for?

The <scope> element can take 6 values: compile, provided, runtime, test, system and import.

This scope is used to limit the transitivity of a dependency, and also to affect the classpath used for various build tasks.

compile

This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.

provided

This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.

runtime

This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.

test

This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

system

This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.

import (only available in Maven 2.0.9 or later)

This scope is only used on a dependency of type pom in the section. It indicates that the specified POM should be replaced with the dependencies in that POM's section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

To answer the second part of your question:

How can we use it for running test?

Note that the test scope allows to use dependencies only for the test phase.

Read the documentation for full details.

Python matplotlib multiple bars

I know that this is about matplotlib, but using pandas and seaborn can save you a lot of time:

df = pd.DataFrame(zip(x*3, ["y"]*3+["z"]*3+["k"]*3, y+z+k), columns=["time", "kind", "data"])
plt.figure(figsize=(10, 6))
sns.barplot(x="time", hue="kind", y="data", data=df)
plt.show()

enter image description here

Is Java "pass-by-reference" or "pass-by-value"?

Java passes primitive types by value and class types by reference

Now, people like to bicker endlessly about whether "pass by reference" is the correct way to describe what Java et al. actually do. The point is this:

  1. Passing an object does not copy the object.
  2. An object passed to a function can have its members modified by the function.
  3. A primitive value passed to a function cannot be modified by the function. A copy is made.

In my book that's called passing by reference.

Brian Bi - Which programming languages are pass by reference?

Appropriate datatype for holding percent values?

Assuming two decimal places on your percentages, the data type you use depends on how you plan to store your percentages. If you are going to store their fractional equivalent (e.g. 100.00% stored as 1.0000), I would store the data in a decimal(5,4) data type with a CHECK constraint that ensures that the values never exceed 1.0000 (assuming that is the cap) and never go below 0 (assuming that is the floor). If you are going to store their face value (e.g. 100.00% is stored as 100.00), then you should use decimal(5,2) with an appropriate CHECK constraint. Combined with a good column name, it makes it clear to other developers what the data is and how the data is stored in the column.

How to submit form on change of dropdown list?

Simple JavaScript will do -

<form action="myservlet.do" method="POST">
    <select name="myselect" id="myselect" onchange="this.form.submit()">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
    </select>
</form>

Here is a link for a good javascript tutorial.

npm start error with create-react-app

I solve this issue by running following command

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

hope it helps

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

Logging with Retrofit 2

Kotlin Code

        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
        val retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        return retrofit.create(PointApi::class.java)

ActiveRecord find and only return selected columns

My answer comes quite late because I'm a pretty new developer. This is what you can do:

Location.select(:name, :website, :city).find(row.id)

Btw, this is Rails 4

How to use a decimal range() step value?

Here's a solution using itertools:

import itertools

def seq(start, end, step):
    if step == 0:
        raise ValueError("step must not be 0")
    sample_count = int(abs(end - start) / step)
    return itertools.islice(itertools.count(start, step), sample_count)

Usage Example:

for i in seq(0, 1, 0.1):
    print(i)

mySQL :: insert into table, data from another table?

for whole row

insert into xyz select * from xyz2 where id="1";

for selected column

insert into xyz(t_id,v_id,f_name) select t_id,v_id,f_name from xyz2 where id="1";

Hide/Show Column in an HTML Table

you could use colgroups:

<table>
    <colgroup>
       <col class="visible_class"/>
       <col class="visible_class"/>
       <col class="invisible_class"/>  
    </colgroup>
    <thead>
        <tr><th class="col1">Header 1</th><th class="col2">Header 2</th><th class="col3">Header 3</th></tr>
    </thead>
    <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
    <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
    <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
    <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
</table>

your script then could change just the desire <col> class.

How to Lazy Load div background images

I've found this on the plugin's official site:

<div class="lazy" data-original="img/bmw_m1_hood.jpg" style="background-image: url('img/grey.gif'); width: 765px; height: 574px;"></div>

$("div.lazy").lazyload({
      effect : "fadeIn"
});

Source: http://www.appelsiini.net/projects/lazyload/enabled_background.html

Remote JMX connection

Had it been on Linux the problem would be that localhost is the loopback interface, you need to application to bind to your network interface.

You can use the netstat to confirm that it is not bound to the expected network interface.

You can make this work by invoking the program with the system parameter java.rmi.server.hostname="YOUR_IP", either as an environment variable or using

java -Djava.rmi.server.hostname=YOUR_IP YOUR_APP

Tomcat in Intellij Idea Community Edition

Intellij Community does not offer Java application server integration. Your alternatives are

  1. buying Intellij licence,
  2. switching to Eclipse ;)
  3. installing Smart Tomcat plugin https://plugins.jetbrains.com/plugin/9492
  4. installing IDEA Jetty Runner plugin https://plugins.jetbrains.com/plugin/7505
  5. running the application server from Maven, Gradle, whatever, as outlined in the other answers.

I personally installed the Jetty Runner plugin (Jetty is fine for me, I do not need Tomcat) and I am satisfied with this solution. I had to deal with IntelliJ idea - Jetty, report an exception, though.

How to add to the end of lines containing a pattern with sed or awk?

In bash:

while read -r line ; do
    [[ $line == all:* ]] && line+=" anotherthing"
    echo "$line"
done < filename

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

Type or namespace name does not exist

And if all else fails, such as ensuring that the target frameworks are the same, and you are dealing with a WPF class library in VS2010, simply restart Visual Studio. That did it for me.

SQLAlchemy insert or update example

assuming certain column names...

INSERT one

newToner = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

dbsession.add(newToner)   
dbsession.commit()

INSERT multiple

newToner1 = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

newToner2 = Toner(toner_id = 2,
                    toner_color = 'red',
                    toner_hex = '#F01731')

dbsession.add_all([newToner1, newToner2])   
dbsession.commit()

UPDATE

q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'

dbsession.commit()

or using a fancy one-liner using MERGE

record = dbsession.merge(Toner( **kwargs))

Numpy Resize/Rescale Image

One-line numpy solution for downsampling (by 2):

smaller_img = bigger_img[::2, ::2]

And upsampling (by 2):

bigger_img = smaller_img.repeat(2, axis=0).repeat(2, axis=1)

(this asssumes HxWxC shaped image. h/t to L. Kärkkäinen in the comments above. note this method only allows whole integer resizing (e.g., 2x but not 1.5x))

Something like 'contains any' for Java set?

I would recommend creating a HashMap from set A, and then iterating through set B and checking if any element of B is in A. This would run in O(|A|+|B|) time (as there would be no collisions), whereas retainAll(Collection<?> c) must run in O(|A|*|B|) time.

How to kill a child process by the parent process?

In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.

When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).

Remember to call wait() on the child process to prevent any lingering zombies.

Change button background color using swift language

U can also play around the tintcolor and button image to indirectly change the color.

Extract a substring from a string in Ruby using a regular expression

You can use a regular expression for that pretty easily…

Allowing spaces around the word (but not keeping them):

str.match(/< ?([^>]+) ?>\Z/)[1]

Or without the spaces allowed:

str.match(/<([^>]+)>\Z/)[1]

Replacing H1 text with a logo image: best method for SEO and accessibility?

If accessibility reasons is important then use the first variant (when customer want to see image without styles)

<div id="logo">
    <a href="">
        <img src="logo.png" alt="Stack Overflow" />
    </a>
</div>

No need to conform imaginary SEO requirements, because the HTML code above has correct structure and only you should decide does this suitable for you visitors.

Also you can use the variant with less HTML code

<h1 id="logo">
  <a href=""><span>Stack Overflow</span></a>
</h1>
/* position code, it may be absolute position or normal - depends on other parts of your site */
#logo {
  ...
}

#logo a {
   display:block;
   width: actual_image_width;
   height: actual_image_height;
   background: url(image.png) no-repeat left top;
}

/* for accessibility reasons - without styles variant*/
#logo a span {display: none}

Please note that I have removed all other CSS styles and hacks because they didn't correspond to the task. They may be usefull in particular cases only.

How can I fetch all items from a DynamoDB table without specifying the primary key?

I fetch all items from dynamodb with the following query. It works fine. i create these function generic in zend framework and access these functions over the project.

        public function getQuerydata($tablename, $filterKey, $filterValue){
            return $this->getQuerydataWithOp($tablename, $filterKey, $filterValue, 'EQ');
        }

        public function getQuerydataWithOp($tablename, $filterKey, $filterValue, $compOperator){
        $result = $this->getClientdb()->query(array(
                'TableName'     => $tablename,
                'IndexName'     => $filterKey,
                'Select'        => 'ALL_ATTRIBUTES',
                'KeyConditions' => array(
                    $filterKey => array(
                        'AttributeValueList' => array(
                            array('S' => $filterValue)
                        ),
                'ComparisonOperator' => $compOperator
            )
            )
        ));
            return $result['Items'];
        }

       //Below i Access these functions and get data.
       $accountsimg = $this->getQuerydataWithPrimary('accounts', 'accountID',$msgdata[0]['accountID']['S']);

'pip' is not recognized as an internal or external command

I continued to receive this error after correcting my PATH.

If your codebase requires that you have an earlier version of Python (2.7 in my case), it may have been a version prior to the existence of pip.

It's not very canonical, but installing a more recent version worked for me. (I used 2.7.13.)

Replace all elements of Python NumPy Array that are greater than some value

Lets us assume you have a numpy array that has contains the value from 0 all the way up to 20 and you want to replace numbers greater than 10 with 0

_x000D_
_x000D_
import numpy as np

my_arr = np.arange(0,21) # creates an array
my_arr[my_arr > 10] = 0 # modifies the value
_x000D_
_x000D_
_x000D_

Note this will however modify the original array to avoid overwriting the original array try using arr.copy() to create a new detached copy of the original array and modify that instead.

_x000D_
_x000D_
import numpy as np

my_arr = np.arange(0,21)
my_arr_copy = my_arr.copy() # creates copy of the orignal array

my_arr_copy[my_arr_copy > 10] = 0 
_x000D_
_x000D_
_x000D_

Is there any free OCR library for Android?

Google Goggles is the perfect application for doing both OCR and translation.
And the good news is that Google Goggles to Become App Platform.

Until then, you can use IQ Engines.

@RequestBody and @ResponseBody annotations in Spring

There is a whole Section in the docs called 16.3.3.4 Mapping the request body with the @RequestBody annotation. And one called 16.3.3.5 Mapping the response body with the @ResponseBody annotation. I suggest you consult those sections. Also relevant: @RequestBody javadocs, @ResponseBody javadocs

Usage examples would be something like this:

Using a JavaScript-library like JQuery, you would post a JSON-Object like this:

{ "firstName" : "Elmer", "lastName" : "Fudd" }

Your controller method would look like this:

// controller
@ResponseBody @RequestMapping("/description")
public Description getDescription(@RequestBody UserStats stats){
    return new Description(stats.getFirstName() + " " + stats.getLastname() + " hates wacky wabbits");
}

// domain / value objects
public class UserStats{
    private String firstName;
    private String lastName;
    // + getters, setters
}
public class Description{
    private String description;
    // + getters, setters, constructor
}

Now if you have Jackson on your classpath (and have an <mvc:annotation-driven> setup), Spring would convert the incoming JSON to a UserStats object from the post body (because you added the @RequestBody annotation) and it would serialize the returned object to JSON (because you added the @ResponseBody annotation). So the Browser / Client would see this JSON result:

{ "description" : "Elmer Fudd hates wacky wabbits" }

See this previous answer of mine for a complete working example: https://stackoverflow.com/a/5908632/342852

Note: RequestBody / ResponseBody is of course not limited to JSON, both can handle multiple formats, including plain text and XML, but JSON is probably the most used format.


Update

Ever since Spring 4.x, you usually won't use @ResponseBody on method level, but rather @RestController on class level, with the same effect.

Here is a quote from the official Spring MVC documentation:

@RestController is a composed annotation that is itself meta-annotated with @Controller and @ResponseBody to indicate a controller whose every method inherits the type-level @ResponseBody annotation and, therefore, writes directly to the response body versus view resolution and rendering with an HTML template.

How to increment a pointer address and pointer's value?

        Note:
        1) Both ++ and * have same precedence(priority), so the associativity comes into picture.
        2) in this case Associativity is from **Right-Left**

        important table to remember in case of pointers and arrays: 

        operators           precedence        associativity

    1)  () , []                1               left-right
    2)  *  , identifier        2               right-left
    3)  <data type>            3               ----------

        let me give an example, this might help;

        char **str;
        str = (char **)malloc(sizeof(char*)*2); // allocate mem for 2 char*
        str[0]=(char *)malloc(sizeof(char)*10); // allocate mem for 10 char
        str[1]=(char *)malloc(sizeof(char)*10); // allocate mem for 10 char

        strcpy(str[0],"abcd");  // assigning value
        strcpy(str[1],"efgh");  // assigning value

        while(*str)
        {
            cout<<*str<<endl;   // printing the string
            *str++;             // incrementing the address(pointer)
                                // check above about the prcedence and associativity
        }
        free(str[0]);
        free(str[1]);
        free(str);

Does Visual Studio Code have box select/multi-line edit?

Press Ctrl+Alt+Down or Ctrl+Alt+Up to insert cursors below or above.

Eclipse "this compilation unit is not on the build path of a java project"

Here the steps for creating a source folder in eclipse.

  1. Right click on the project and go to properties
  2. Select "Java Build Path" from the properties dialog box
  3. Select the source tab and check that the source folders are correct if not click on the remove button to remove source folders, or the add button to add source folders.

You can control the order in which source folders appear in a project on order and export tab on the configure build path option.

Getting multiple keys of specified value of a generic Dictionary?

As a twist of the accepted answer (https://stackoverflow.com/a/255638/986160) assuming that the keys will be associated with signle values in the dictionary. Similar to (https://stackoverflow.com/a/255630/986160) but a bit more elegant. The novelty is in that the consuming class can be used as an enumeration alternative (but for strings too) and that the dictionary implements IEnumerable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace MyApp.Dictionaries
{

    class BiDictionary<TFirst, TSecond> : IEnumerable
    {
        IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
        IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();

        public void Add(TFirst first, TSecond second)
        {
            firstToSecond.Add(first, second);
            secondToFirst.Add(second, first);
        }

        public TSecond this[TFirst first]
        {
            get { return GetByFirst(first); }
        }

        public TFirst this[TSecond second]
        {
            get { return GetBySecond(second); }
        }

        public TSecond GetByFirst(TFirst first)
        {
            return firstToSecond[first];
        }

        public TFirst GetBySecond(TSecond second)
        {
            return secondToFirst[second];
        }

        public IEnumerator GetEnumerator()
        {
            return GetFirstEnumerator();
        }

        public IEnumerator GetFirstEnumerator()
        {
            return firstToSecond.GetEnumerator();
        }

        public IEnumerator GetSecondEnumerator()
        {
            return secondToFirst.GetEnumerator();
        }
    }
}

And as a consuming class you could have

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyApp.Dictionaries
{
    class Greek
    {

        public static readonly string Alpha = "Alpha";
        public static readonly string Beta = "Beta";
        public static readonly string Gamma = "Gamma";
        public static readonly string Delta = "Delta";


        private static readonly BiDictionary<int, string> Dictionary = new BiDictionary<int, string>();


        static Greek() {
            Dictionary.Add(1, Alpha);
            Dictionary.Add(2, Beta);
            Dictionary.Add(3, Gamma);
            Dictionary.Add(4, Delta);
        }

        public static string getById(int id){
            return Dictionary.GetByFirst(id);
        }

        public static int getByValue(string value)
        {
            return Dictionary.GetBySecond(value);
        }

    }
}

Failed to load resource: the server responded with a status of 404 (Not Found)

Your files are not under the jsp folder that's why it is not found. You have to go back again 1 folder Try this:

     <script  src="../../Jquery/prettify.js"></script>

Minimal web server using netcat

LOL, a super lame hack, but at least curl and firefox accepts it:

while true ; do (dd if=/dev/zero count=10000;echo -e "HTTP/1.1\n\n $(date)") | nc -l  1500  ; done

You better replace it soon with something proper!

Ah yes, my nc were not exactly the same as yours, it did not like the -p option.

Convert negative data into positive data in SQL Server

UPDATE mytbl
SET a = ABS(a)
where a < 0

Create a folder inside documents folder in iOS apps

This works fine for me,

NSFileManager *fm = [NSFileManager defaultManager];
NSArray *appSupportDir = [fm URLsForDirectory:NSDocumentsDirectory inDomains:NSUserDomainMask];
NSURL* dirPath = [[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:@"YourFolderName"];

NSError*    theError = nil; //error setting
if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES
                           attributes:nil error:&theError])
{
   NSLog(@"not created");
}

String.Format not work in TypeScript

String Interpolation

Note: As of TypeScript 1.4, string interpolation is available in TypeScript:

var a = "Hello";
var b = "World";

var text = `${a} ${b}`

This will compile to:

var a = "Hello";
var b = "World";
var text = a + " " + b;

String Format

The JavaScript String object doesn't have a format function. TypeScript doesn't add to the native objects, so it also doesn't have a String.format function.

For TypeScript, you need to extend the String interface and then you need to supply an implementation:

interface String {
    format(...replacements: string[]): string;
}

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

You can then use the feature:

var myStr = 'This is an {0} for {0} purposes: {1}';

alert(myStr.format('example', 'end'));

You could also consider string interpolation (a feature of Template Strings), which is an ECMAScript 6 feature - although to use it for the String.format use case, you would still need to wrap it in a function in order to supply a raw string containing the format and then positional arguments. It is more typically used inline with the variables that are being interpolated, so you'd need to map using arguments to make it work for this use case.

For example, format strings are normally defined to be used later... which doesn't work:

// Works
var myFormatString = 'This is an {0} for {0} purposes: {1}';

// Compiler warnings (a and b not yet defines)
var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;

So to use string interpolation, rather than a format string, you would need to use:

function myTemplate(a: string, b: string) {
    var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;
}

alert(myTemplate('example', 'end'));

The other common use case for format strings is that they are used as a resource that is shared. I haven't yet discovered a way to load a template string from a data source without using eval.

Insert text with single quotes in PostgreSQL

This is so many worlds of bad, because your question implies that you probably have gaping SQL injection holes in your application.

You should be using parameterized statements. For Java, use PreparedStatement with placeholders. You say you don't want to use parameterised statements, but you don't explain why, and frankly it has to be a very good reason not to use them because they're the simplest, safest way to fix the problem you are trying to solve.

See Preventing SQL Injection in Java. Don't be Bobby's next victim.

There is no public function in PgJDBC for string quoting and escaping. That's partly because it might make it seem like a good idea.

There are built-in quoting functions quote_literal and quote_ident in PostgreSQL, but they are for PL/PgSQL functions that use EXECUTE. These days quote_literal is mostly obsoleted by EXECUTE ... USING, which is the parameterised version, because it's safer and easier. You cannot use them for the purpose you explain here, because they're server-side functions.


Imagine what happens if you get the value ');DROP SCHEMA public;-- from a malicious user. You'd produce:

insert into test values (1,'');DROP SCHEMA public;--');

which breaks down to two statements and a comment that gets ignored:

insert into test values (1,'');
DROP SCHEMA public;
--');

Whoops, there goes your database.

What is this CSS selector? [class*="span"]

.show-grid [class*="span"]

It's a CSS selector that selects all elements with the class show-grid that has a child element whose class contains the name span.

Need to find a max of three numbers in java

You should know more about java.lang.Math.max:

  1. java.lang.Math.max(arg1,arg2) only accepts 2 arguments but you are writing 3 arguments in your code.
  2. The 2 arguments should be double,int,long and float but your are writing String arguments in Math.max function. You need to parse them in the required type.

You code will produce compile time error because of above mismatches.

Try following updated code, that will solve your purpose:

import java.lang.Math;
import java.util.Scanner;
public class max {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please input 3 integers: ");
        int x = Integer.parseInt(keyboard.nextLine());
        int y = Integer.parseInt(keyboard.nextLine());
        int z = Integer.parseInt(keyboard.nextLine());
        int max = Math.max(x,y);
        if(max>y){ //suppose x is max then compare x with z to find max number
            max = Math.max(x,z);    
        }
        else{ //if y is max then compare y with z to find max number
            max = Math.max(y,z);    
        }
        System.out.println("The max of three is: " + max);
    }
} 

Method List in Visual Studio Code

ctrl+shift+o // This should work for javascript files by default

For PHP install the extension PHP SYMBOLS

FOR PYTHON install the extension PYTHON

On Reload, this will work fine

How to detect when an Android app goes to the background and come back to the foreground

2018: Android supports this natively through lifecycle components.

March 2018 UPDATE: There is now a better solution. See ProcessLifecycleOwner. You will need to use the new architecture components 1.1.0 (latest at this time) but it’s specifically designed to do this.

There’s a simple sample provided in this answer but I wrote a sample app and a blog post about it.

Ever since I wrote this back in 2014, different solutions arose. Some worked, some were thought to be working, but had flaws (including mine!) and we, as a community (Android) learned to live with the consequences and wrote workarounds for the special cases.

Never assume a single snippet of code is the solution you’re looking for, it’s unlikely the case; better yet, try to understand what it does and why it does it.

The MemoryBoss class was never actually used by me as written here, it was just a piece of pseudo code that happened to work.

Unless there’s valid reason for you not to use the new architecture components (and there are some, especially if you target super old apis), then go ahead and use them. They are far from perfect, but neither were ComponentCallbacks2.

UPDATE / NOTES (November 2015): People has been making two comments, first is that >= should be used instead of == because the documentation states that you shouldn't check for exact values. This is fine for most cases, but bear in mind that if you only care about doing something when the app went to the background, you will have to use == and also combine it with another solution (like Activity Lifecycle callbacks), or you may not get your desired effect. The example (and this happened to me) is that if you want to lock your app with a password screen when it goes to the background (like 1Password if you're familiar with it), you may accidentally lock your app if you run low on memory and are suddenly testing for >= TRIM_MEMORY, because Android will trigger a LOW MEMORY call and that's higher than yours. So be careful how/what you test.

Additionally, some people have asked about how to detect when you get back.

The simplest way I can think of is explained below, but since some people are unfamiliar with it, I'm adding some pseudo code right here. Assuming you have YourApplication and the MemoryBoss classes, in your class BaseActivity extends Activity (you will need to create one if you don't have one).

@Override
protected void onStart() {
    super.onStart();

    if (mApplication.wasInBackground()) {
        // HERE YOU CALL THE CODE YOU WANT TO HAPPEN ONLY ONCE WHEN YOUR APP WAS RESUMED FROM BACKGROUND
        mApplication.setWasInBackground(false);
    }
}

I recommend onStart because Dialogs can pause an activity so I bet you don't want your app to think "it went to the background" if all you did was display a full screen dialog, but your mileage may vary.

And that's all. The code in the if block will only be executed once, even if you go to another activity, the new one (that also extends BaseActivity) will report wasInBackground is false so it won't execute the code, until onMemoryTrimmed is called and the flag is set to true again.

Hope that helps.

UPDATE / NOTES (April 2015): Before you go all Copy and Paste on this code, note that I have found a couple of instances where it may not be 100% reliable and must be combined with other methods to achieve the best results. Notably, there are two known instances where the onTrimMemory call back is not guaranteed to be executed:

  1. If your phone locks the screen while your app is visible (say your device locks after nn minutes), this callback is not called (or not always) because the lockscreen is just on top, but your app is still "running" albeit covered.

  2. If your device is relatively low on memory (and under memory stress), the Operating System seems to ignore this call and go straight to more critical levels.

Now, depending how important it's for you to know when your app went to the background, you may or may not need to extend this solution together with keeping track of the activity lifecycle and whatnot.

Just keep the above in mind and have a good QA team ;)

END OF UPDATE

It may be late but there's a reliable method in Ice Cream Sandwich (API 14) and Above.

Turns out that when your app has no more visible UI, a callback is triggered. The callback, which you can implement in a custom class, is called ComponentCallbacks2 (yes, with a two). This callback is only available in API Level 14 (Ice Cream Sandwich) and above.

You basically get a call to the method:

public abstract void onTrimMemory (int level)

The Level is 20 or more specifically

public static final int TRIM_MEMORY_UI_HIDDEN

I've been testing this and it always works, because level 20 is just a "suggestion" that you might want to release some resources since your app is no longer visible.

To quote the official docs:

Level for onTrimMemory(int): the process had been showing a user interface, and is no longer doing so. Large allocations with the UI should be released at this point to allow memory to be better managed.

Of course, you should implement this to actually do what it says (purge memory that hasn't been used in certain time, clear some collections that have been sitting unused, etc. The possibilities are endless (see the official docs for other possible more critical levels).

But, the interesting thing, is that the OS is telling you: HEY, your app went to the background!

Which is exactly what you wanted to know in the first place.

How do you determine when you got back?

Well that's easy, I'm sure you have a "BaseActivity" so you can use your onResume() to flag the fact that you're back. Because the only time you will be saying you're not back is when you actually receive a call to the above onTrimMemory method.

It works. You don't get false positives. If an activity is resuming, you're back, 100% of the times. If the user goes to the back again, you get another onTrimMemory() call.

You need to suscribe your Activities (or better yet, a custom class).

The easiest way to guarantee that you always receive this is to create a simple class like this:

public class MemoryBoss implements ComponentCallbacks2 {
    @Override
    public void onConfigurationChanged(final Configuration newConfig) {
    }

    @Override
    public void onLowMemory() {
    }

    @Override
    public void onTrimMemory(final int level) {
        if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
            // We're in the Background
        }
        // you might as well implement some memory cleanup here and be a nice Android dev.
    }
}

In order to use this, in your Application implementation (you have one, RIGHT?), do something like:

MemoryBoss mMemoryBoss;
@Override
public void onCreate() {
   super.onCreate();
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
      mMemoryBoss = new MemoryBoss();
      registerComponentCallbacks(mMemoryBoss);
   } 
}

If you create an Interface you could add an else to that if and implement ComponentCallbacks (without the 2) used in anything below API 14. That callback only has the onLowMemory() method and does not get called when you go to the background, but you should use it to trim memory.

Now launch your App and press home. Your onTrimMemory(final int level) method should be called (hint: add logging).

The last step is to unregister from the callback. Probably the best place is the onTerminate() method of your App, but, that method doesn't get called on a real device:

/**
 * This method is for use in emulated process environments.  It will
 * never be called on a production Android device, where processes are
 * removed by simply killing them; no user code (including this callback)
 * is executed when doing so.
 */

So unless you really have a situation where you no longer want to be registered, you can safety ignore it, since your process is dying at OS level anyway.

If you decide to unregister at some point (if you, for example, provide a shutdown mechanism for your app to clean up and die), you can do:

unregisterComponentCallbacks(mMemoryBoss);

And that's it.

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

For..In loops in JavaScript - key value pairs

Please try the below code:

<script> 
 const games = {
  "Fifa": "232",
  "Minecraft": "476",
  "Call of Duty": "182"
 };

Object.keys(games).forEach((item, index, array) => {
  var msg = item+' '+games[item];
  console.log(msg);
});

Oracle SqlDeveloper JDK path

For those who use Mac, edit this file:

/Applications/SQLDeveloper.app/Contents/MacOS/sqldeveloper.sh

Mine had:

export JAVA_HOME=`/usr/libexec/java_home -v 1.7`

and I changed it to 1.8 and it stopped complaining about java version.

Sending multipart/formdata with jQuery.ajax

Just wanted to add a bit to Raphael's great answer. Here's how to get PHP to produce the same $_FILES, regardless of whether you use JavaScript to submit.

HTML form:

<form enctype="multipart/form-data" action="/test.php" 
method="post" class="putImages">
   <input name="media[]" type="file" multiple/>
   <input class="button" type="submit" alt="Upload" value="Upload" />
</form>

PHP produces this $_FILES, when submitted without JavaScript:

Array
(
    [media] => Array
        (
            [name] => Array
                (
                    [0] => Galata_Tower.jpg
                    [1] => 518f.jpg
                )

            [type] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => /tmp/phpIQaOYo
                    [1] => /tmp/phpJQaOYo
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 258004
                    [1] => 127884
                )

        )

)

If you do progressive enhancement, using Raphael's JS to submit the files...

var data = new FormData($('input[name^="media"]'));     
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
    data.append(i, file);
});

$.ajax({
    type: ppiFormMethod,
    data: data,
    url: ppiFormActionURL,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data){
        alert(data);
    }
});

... this is what PHP's $_FILES array looks like, after using that JavaScript to submit:

Array
(
    [0] => Array
        (
            [name] => Galata_Tower.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpAQaOYo
            [error] => 0
            [size] => 258004
        )

    [1] => Array
        (
            [name] => 518f.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpBQaOYo
            [error] => 0
            [size] => 127884
        )

)

That's a nice array, and actually what some people transform $_FILES into, but I find it's useful to work with the same $_FILES, regardless if JavaScript was used to submit. So, here are some minor changes to the JS:

// match anything not a [ or ]
regexp = /^[^[\]]+/;
var fileInput = $('.putImages input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );

// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
    data.append(fileInputName+'['+i+']', file);
});

(14 April 2017 edit: I removed the form element from the constructor of FormData() -- that fixed this code in Safari.)

That code does two things.

  1. Retrieves the input name attribute automatically, making the HTML more maintainable. Now, as long as form has the class putImages, everything else is taken care of automatically. That is, the input need not have any special name.
  2. The array format that normal HTML submits is recreated by the JavaScript in the data.append line. Note the brackets.

With these changes, submitting with JavaScript now produces precisely the same $_FILES array as submitting with simple HTML.

Add event handler for body.onload by javascript within <body> part

You should really use the following instead (works in all newer browsers):

window.addEventListener('DOMContentLoaded', init, false);

How to change the font and font size of an HTML input tag?

In your 'head' section, add this code:

<style>
input[type='text'] { font-size: 24px; }
</style>

Or you can only add the:

input[type='text'] { font-size: 24px; }

to a CSS file which can later be included.

You can also change the font face by using the CSS property: font-family

font-family: monospace;

So you can have a CSS code like this:

input[type='text'] { font-size: 24px; font-family: monospace; }

You can find further help at the W3Schools website.

I suggest you to have a look at the CSS3 specification. With CSS3 you can also load a font from the web instead of having the limitation to use only the most common fonts or tell the user to download the font you're using.

VBScript to send email without running Outlook

Yes. Blat or any other self contained SMTP mailer. Blat is a fairly full featured SMTP client that runs from command line

Blat is here

Is it possible to use the instanceof operator in a switch statement?

This is a typical scenario where subtype polymorphism helps. Do the following

interface I {
  void do();
}

class A implements I { void do() { doA() } ... }
class B implements I { void do() { doB() } ... }
class C implements I { void do() { doC() } ... }

Then you can simply call do() on this.

If you are not free to change A, B, and C, you could apply the visitor pattern to achieve the same.

Disabling the long-running-script message in Internet Explorer

This message displays when Internet Explorer reaches the maximum number of synchronous instructions for a piece of JavaScript. The default maximum is 5,000,000 instructions, you can increase this number on a single machine by editing the registry.

Internet Explorer now tracks the total number of executed script statements and resets the value each time that a new script execution is started, such as from a timeout or from an event handler, for the current page with the script engine. Internet Explorer displays a "long-running script" dialog box when that value is over a threshold amount.

The only way to solve the problem for all users that might be viewing your page is to break up the number of iterations your loop performs using timers, or refactor your code so that it doesn't need to process as many instructions.

Breaking up a loop with timers is relatively straightforward:

var i=0;
(function () {
    for (; i < 6000000; i++) {
        /*
            Normal processing here
        */

        // Every 100,000 iterations, take a break
        if ( i > 0 && i % 100000 == 0) {
            // Manually increment `i` because we break
            i++;
            // Set a timer for the next iteration 
            window.setTimeout(arguments.callee);
            break;
        }
    }
})();

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Plenty of responses already, but you can use this:

Sub runQry(qDefName)
    Dim db As DAO.Database, qd As QueryDef, par As Parameter

    Set db = CurrentDb
    Set qd = db.QueryDefs(qDefName)

    On Error Resume Next
    For Each par In qd.Parameters
        Err.Clear
        par.Value = Eval(par.Name)          'try evaluating param
        If Err.Number <> 0 Then             'failed ?
            par.Value = InputBox(par.Name)  'ask for value
        End If
    Next par
    On Error GoTo 0

    qd.Execute dbFailOnError
End Sub

Sub runQry_test()
    runQry "test"  'qryDef name
End Sub

How to format date in angularjs

This isn't really exactly what you are asking for - but you could try creating a date input field in html something like:

<input type="date" ng-model="myDate" />

Then to print this on the page you would use:

<span ng-bind="convertToDate(myDate) | date:'medium'"></span>

Finally, in my controller I declared a method that creates a date from the input value (which in chrome is apparently parsed 1 day off):

$scope.convertToDate = function (stringDate){
  var dateOut = new Date(stringDate);
  dateOut.setDate(dateOut.getDate() + 1);
  return dateOut;
};

So there you have it. To see the whole thing working see the following plunker: http://plnkr.co/edit/8MVoXNaIDW59kQnfpaWW?p=preview .Best of luck!

Check element CSS display with JavaScript

For jQuery, do you mean like this?

$('#object').css('display');

You can check it like this:

if($('#object').css('display') === 'block')
{
    //do something
}
else
{
    //something else
}

PHP Session data not being saved

Here is one common problem I haven't seen addressed in the other comments: is your host running a cache of some sort? If they are automatically caching results in some fashion you would get this sort of behavior.

Python: Random numbers into a list

my_randoms = [randint(n1,n2) for x in range(listsize)]

How do I set response headers in Flask?

This work for me

from flask import Flask
from flask import Response

app = Flask(__name__)

@app.route("/")
def home():
    return Response(headers={'Access-Control-Allow-Origin':'*'})

if __name__ == "__main__":
    app.run()

PowerShell to remove text from a string

$a="some text =keep this,but not this"
$a.split('=')[1].split(',')[0]

returns

keep this

What is the <leader> in a .vimrc file?

The "Leader key" is a way of extending the power of VIM's shortcuts by using sequences of keys to perform a command. The default leader key is backslash. Therefore, if you have a map of <Leader>Q, you can perform that action by typing \Q.

Pass C# ASP.NET array to Javascript array

Simple

The array of integers is quite simple to pass. However this solution works for more complex data as well. In your model:

public int[] Numbers => new int[5];

In your view:

numbers = @(new HtmlString(JsonSerializer.Serialize(Model.Numbers)))

Optional

A tip for passing strings. You may want JSON encoder to not escape some symbols in your strings. In this example I want raw unescaped cyrillic letters. In your view:

strings = @(
new HtmlString(
    JsonSerializer.Serialize(Model.Strings, new JsonSerializerOptions
    {
        Encoder = JavaScriptEncoder.Create(
            UnicodeRanges.BasicLatin,
            UnicodeRanges.Cyrillic)
    })))

Set transparent background using ImageMagick and commandline prompt

Yep. Had this same problem too. Here's the command I ran and it worked perfectly: convert transparent-img1.png transparent-img2.png transparent-img3.png -channel Alpha favicon.ico

Permission denied when launch python script via bash

I'm a Ubuntu user and I had the same issue, when I was trying to run python script through a bash script while files were located in a NTFS partition (even with su didn't work) then I've moved it home (ext4) then it worked.

Ajax post request in laravel 5 return error 500 (Internal Server Error)

I guess this has been solved by now but still the best thing to do here is to send the token with your form

{!! csrf_field() !!}

and then in your ajax

$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
    url: "test",
    type:"POST",
    data: { '_token': token, 'someOtherData': someOtherData },
    success:function(data){
        alert(data);
    },error:function(){ 
        alert("error!!!!");
    }
}); //end of ajax
});

LINQ Using Max() to select a single row

More one example:

Follow:

 qryAux = (from q in qryAux where
            q.OrdSeq == (from pp in Sessao.Query<NameTable>() where pp.FieldPk
            == q.FieldPk select pp.OrdSeq).Max() select q);

Equals:

 select t.*   from nametable t  where t.OrdSeq =
        (select max(t2.OrdSeq) from nametable t2 where t2.FieldPk= t.FieldPk)

Finding a substring within a list in Python

print [s for s in list if sub in s]

If you want them separated by newlines:

print "\n".join(s for s in list if sub in s)

Full example, with case insensitivity:

mylist = ['abc123', 'def456', 'ghi789', 'ABC987', 'aBc654']
sub = 'abc'

print "\n".join(s for s in mylist if sub.lower() in s.lower())

Difference between .dll and .exe?

EXE:

  1. It's a executable file
  2. When loading an executable, no export is called, but only the module entry point.
  3. When a system launches new executable, a new process is created
  4. The entry thread is called in context of main thread of that process.

DLL:

  1. It's a Dynamic Link Library
  2. There are multiple exported symbols.
  3. The system loads a DLL into the context of an existing process.

For More Details: http://www.c-sharpcorner.com/Interviews/Answer/Answers.aspxQuestionId=1431&MajorCategoryId=1&MinorCategoryId=1 http://wiki.answers.com/Q/What_is_the_difference_between_an_EXE_and_a_DLL

Reference: http://www.dotnetspider.com/forum/34260-What-difference-between-dll-exe.aspx

Want to upgrade project from Angular v5 to Angular v6

Angular 6 has just been released.

https://blog.angular.io/version-6-of-angular-now-available-cc56b0efa7a4

Here is what worked for one of my smaller projects

  1. npm install -g @angular/cli
  2. npm install @angular/cli
  3. ng update @angular/cli --migrate-only --from=1.7.0
  4. ng update @angular/core
  5. npm install rxjs-compat
  6. ng serve

You might need to update your run scripts in package.json For eg. if you use flags like "app" and "environment" These have been updated to "project" and "configuration" respectively.

Refer https://update.angular.io/ for more detailed guide.

Android webview launches browser when calling loadurl

Answering my question based on the suggestions from Maudicus and Hit.

Check the WebView tutorial here. Just implement the web client and set it before loadUrl. The simplest way is:

myWebView.setWebViewClient(new WebViewClient());

For more advanced processing for the web content, consider the ChromeClient.

How to get a list column names and datatypes of a table in PostgreSQL?

SELECT column_name,data_type 
FROM information_schema.columns 
WHERE
table_name = 'your_table_name' 
AND table_catalog = 'your_database_name' 
AND table_schema = 'your_schema_name';

How do I create a Python function with optional arguments?

Just use the *args parameter, which allows you to pass as many arguments as you want after your a,b,c. You would have to add some logic to map args->c,d,e,f but its a "way" of overloading.

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

And it will print values of c,d,e,f


Similarly you could use the kwargs argument and then you could name your parameters.

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

And then kwargs would have a dictionary of all the parameters that are key valued after a,b

How to slice an array in Bash

Array slicing like in Python (From the rebash library):

array_slice() {
    local __doc__='
    Returns a slice of an array (similar to Python).

    From the Python documentation:
    One way to remember how slices work is to think of the indices as pointing
    between elements, with the left edge of the first character numbered 0.
    Then the right edge of the last element of an array of length n has
    index n, for example:
    ```
    +---+---+---+---+---+---+
    | 0 | 1 | 2 | 3 | 4 | 5 |
    +---+---+---+---+---+---+
    0   1   2   3   4   5   6
    -6  -5  -4  -3  -2  -1
    ```

    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 1:-2 "${a[@]}")
    1 2 3
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 0:1 "${a[@]}")
    0
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice 1:1 "${a[@]}")" ] && echo empty
    empty
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice 2:1 "${a[@]}")" ] && echo empty
    empty
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice -2:-3 "${a[@]}")" ] && echo empty
    empty
    >>> [ -z "$(array.slice -2:-2 "${a[@]}")" ] && echo empty
    empty

    Slice indices have useful defaults; an omitted first index defaults to
    zero, an omitted second index defaults to the size of the string being
    sliced.
    >>> local a=(0 1 2 3 4 5)
    >>> # from the beginning to position 2 (excluded)
    >>> echo $(array.slice 0:2 "${a[@]}")
    >>> echo $(array.slice :2 "${a[@]}")
    0 1
    0 1

    >>> local a=(0 1 2 3 4 5)
    >>> # from position 3 (included) to the end
    >>> echo $(array.slice 3:"${#a[@]}" "${a[@]}")
    >>> echo $(array.slice 3: "${a[@]}")
    3 4 5
    3 4 5

    >>> local a=(0 1 2 3 4 5)
    >>> # from the second-last (included) to the end
    >>> echo $(array.slice -2:"${#a[@]}" "${a[@]}")
    >>> echo $(array.slice -2: "${a[@]}")
    4 5
    4 5

    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -4:-2 "${a[@]}")
    2 3

    If no range is given, it works like normal array indices.
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -1 "${a[@]}")
    5
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -2 "${a[@]}")
    4
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 0 "${a[@]}")
    0
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 1 "${a[@]}")
    1
    >>> local a=(0 1 2 3 4 5)
    >>> array.slice 6 "${a[@]}"; echo $?
    1
    >>> local a=(0 1 2 3 4 5)
    >>> array.slice -7 "${a[@]}"; echo $?
    1
    '
    local start end array_length length
    if [[ $1 == *:* ]]; then
        IFS=":"; read -r start end <<<"$1"
        shift
        array_length="$#"
        # defaults
        [ -z "$end" ] && end=$array_length
        [ -z "$start" ] && start=0
        (( start < 0 )) && let "start=(( array_length + start ))"
        (( end < 0 )) && let "end=(( array_length + end ))"
    else
        start="$1"
        shift
        array_length="$#"
        (( start < 0 )) && let "start=(( array_length + start ))"
        let "end=(( start + 1 ))"
    fi
    let "length=(( end - start ))"
    (( start < 0 )) && return 1
    # check bounds
    (( length < 0 )) && return 1
    (( start < 0 )) && return 1
    (( start >= array_length )) && return 1
    # parameters start with $1, so add 1 to $start
    let "start=(( start + 1 ))"
    echo "${@: $start:$length}"
}
alias array.slice="array_slice"

Make sure that the controller has a parameterless public constructor error

If you have an interface in your controller

public myController(IXInterface Xinstance){}

You must register them to Dependency Injection container.

container.Bind<IXInterface>().To<XClass>().InRequestScope();

use of entityManager.createNativeQuery(query,foo.class)

What you do is called a projection. That's when you return only a scalar value that belongs to one entity. You can do this with JPA. See scalar value.

I think in this case, omitting the entity type altogether is possible:

   Query query = em.createNativeQuery(  "select id from users where username = ?");  
   query.setParameter(1, "lt");  
   BigDecimal val = (BigDecimal) query.getSingleResult(); 

Example taken from here.

How to determine whether a Pandas Column contains a particular value

found = df[df['Column'].str.contains('Text_to_search')]
print(found.count())

the found.count() will contains number of matches

And if it is 0 then means string was not found in the Column.

What is the Swift equivalent of respondsToSelector?

I guess you want to make a default implementation for delegate. You can do this:

let defaultHandler = {}
(delegate?.method ?? defaultHandler)()

How to get the squared symbol (²) to display in a string

Not sure what kind of text box you are refering to. However, I'm not sure if you can do this in a text box on a user form.

A text box on a sheet you can though.

Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Text = "R2=" & variable
Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Characters(2, 1).Font.Superscript = msoTrue

And same thing for an excel cell

Sheets("Sheet1").Range("A1").Characters(2, 1).Font.Superscript = True

If this isn't what you're after you will need to provide more information in your question.

EDIT: posted this after the comment sorry

How to align content of a div to the bottom

If you're not worried about legacy browsers use a flexbox.

The parent element needs its display type set to flex

div.parent {
  display: flex;
  height: 100%;
}

Then you set the child element's align-self to flex-end.

span.child {
  display: inline-block;
  align-self: flex-end;
}

Here's the resource I used to learn: http://css-tricks.com/snippets/css/a-guide-to-flexbox/

How to install SimpleJson Package for Python

Really simple way is:

pip install simplejson

Get DOM content of cross-domain iframe

If you have access to the iframed page you could use something like easyXDM to make function calls in the iframe and return the data.

If you don't have access to the iframed page you will have to use a server side solution. With PHP you could do something quick and dirty like:

    <?php echo file_get_contents('http://url_of_the_iframe/content.php'); ?> 

C++: Rounding up to the nearest multiple of a number

I think this works:

int roundUp(int numToRound, int multiple) {
    return multiple? !(numToRound%multiple)? numToRound : ((numToRound/multiple)+1)*multiple: numToRound;
}

How do I get the current username in .NET using C#?

I tried several combinations from existing answers, but they were giving me

DefaultAppPool
IIS APPPOOL
IIS APPPOOL\DefaultAppPool

I ended up using

string vUserName = User.Identity.Name;

Which gave me the actual users domain username only.

Using a string variable as a variable name

You can use exec for that:

>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>> 

SOAP vs REST (differences)

IMHO you can't compare SOAP and REST where those are two different things.

SOAP is a protocol and REST is a software architectural pattern. There is a lot of misconception in the internet for SOAP vs REST.

SOAP defines XML based message format that web service-enabled applications use to communicate each other over the internet. In order to do that the applications need prior knowledge of the message contract, datatypes, etc..

REST represents the state(as resources) of a server from an URL.It is stateless and clients should not have prior knowledge to interact with server beyond the understanding of hypermedia.

Make a link use POST instead of GET

I suggest a more dynamic approach, without html coding into the page, keep it strictly JS:

$("a.AS-POST").on('click', e => {
  e.preventDefault()
  let frm = document.createElement('FORM')
  frm.id='frm_'+Math.random()
  frm.method='POST'
  frm.action=e.target.href
  document.body.appendChild(frm)
  frm.submit()
})

Plot a legend outside of the plotting area in base graphics?

Adding another simple alternative that is quite elegant in my opinion.

Your plot:

plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")

Legend:

legend("bottomright", c("group A", "group B"), pch=c(1,2), lty=c(1,2),
       inset=c(0,1), xpd=TRUE, horiz=TRUE, bty="n"
       )

Result:

picture with legend

Here only the second line of the legend was added to your example. In turn:

  • inset=c(0,1) - moves the legend by fraction of plot region in (x,y) directions. In this case the legend is at "bottomright" position. It is moved by 0 plotting regions in x direction (so stays at "right") and by 1 plotting region in y direction (from bottom to top). And it so happens that it appears right above the plot.
  • xpd=TRUE - let's the legend appear outside of plotting region.
  • horiz=TRUE - instructs to produce a horizontal legend.
  • bty="n" - a style detail to get rid of legend bounding box.

Same applies when adding legend to the side:

par(mar=c(5,4,2,6))
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")

legend("topleft", c("group A", "group B"), pch=c(1,2), lty=c(1,2),
       inset=c(1,0), xpd=TRUE, bty="n"
       )

Here we simply adjusted legend positions and added additional margin space to the right side of the plot. Result:

picture with legend 2