Programs & Examples On #Developer tools

A developer tool is an application used to write, edit, or debug another application, or web site. There are varying kinds of developer tools, from fully blown IDEs, to single purpose tools.

What does status=canceled for a resource mean in Chrome Developer Tools?

In my case, it started coming after chrome 76 update.

Due to some issue in my JS code, window.location was getting updated multiple times which resulted in canceling previous request. Although the issue was present from before, chrome started cancelling request after update to version 76.

How can I reduce the waiting (ttfb) time

I would suggest you read this article and focus more on how to optimize the overall response to the user request (either a page, a search result etc.)

A good argument for this is the example they give about using gzip to compress the page. Even though ttfb is faster when you do not compress, the overall experience of the user is worst because it takes longer to download content that is not zipped.

Calling a Javascript Function from Console

I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect:

function indirect(js) { return eval(js); }

With that function in each module, you can then execute any code in the context of it.

E.g. if you had this import in your module:

import { imported_fn } from "./import.js";

You could then get the results of calling imported_fn from the console by doing this:

indirect("imported_fn()");

Using eval was my first thought, but it doesn't work. My hypothesis is that calling eval from the console remains in the context of console, and we need to execute in the context of the module.

event Action<> vs event EventHandler<>

Based on some of the previous answers, I'm going to break my answer down into three areas.

First, physical limitations of using Action<T1, T2, T2... > vs using a derived class of EventArgs. There are three: First, if you change the number or types of parameters, every method that subscribes to will have to be changed to conform to the new pattern. If this is a public facing event that 3rd party assemblies will be using, and there is any possiblity that the event args would change, this would be a reason to use a custom class derived from event args for consistencies sake (remember, you COULD still use an Action<MyCustomClass>) Second, using Action<T1, T2, T2... > will prevent you from passing feedback BACK to the calling method unless you have a some kind of object (with a Handled property for instance) that is passed along with the Action. Third, you don't get named parameters, so if you're passing 3 bool's an int, two string's, and a DateTime, you have no idea what the meaning of those values are. As a side note, you can still have a "Fire this event safely method while still using Action<T1, T2, T2... >".

Secondly, consistency implications. If you have a large system you're already working with, it's nearly always better to follow the way the rest of the system is designed unless you have an very good reason not too. If you have publicly facing events that need to be maintained, the ability to substitute derived classes can be important. Keep that in mind.

Thirdly, real life practice, I personally find that I tend to create a lot of one off events for things like property changes that I need to interact with (Particularly when doing MVVM with view models that interact with each other) or where the event has a single parameter. Most of the time these events take on the form of public event Action<[classtype], bool> [PropertyName]Changed; or public event Action SomethingHappened;. In these cases, there are two benefits. First, I get a type for the issuing class. If MyClass declares and is the only class firing the event, I get an explicit instance of MyClass to work with in the event handler. Secondly, for simple events such as property change events, the meaning of the parameters is obvious and stated in the name of the event handler and I don't have to create a myriad of classes for these kinds of events.

Undo git pull, how to bring repos to old state

it works first use: git reflog

find your SHA of your previus state and make (HEAD@{1} is an example)

git reset --hard HEAD@{1}

Linux Command History with date and time

Try this:

> HISTTIMEFORMAT="%d/%m/%y %T "

> history

You can adjust the format to your liking, of course.

How can I display a JavaScript object?

Use this:

console.log('print object: ' + JSON.stringify(session));

How do I run a docker instance from a DockerFile?

While other answers were usable, this really helped me, so I am putting it also here.

From the documentation:

Instead of specifying a context, you can pass a single Dockerfile in the URL or pipe the file in via STDIN. To pipe a Dockerfile from STDIN:

$ docker build - < Dockerfile

With Powershell on Windows, you can run:

Get-Content Dockerfile | docker build -

When the build is done, run command:

docker image ls

You will see something like this:

REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
<none>                     <none>              123456789        39 seconds ago      422MB

Copy your actual IMAGE ID and then run

docker run 123456789

Where the number at the end is the actual Image ID from previous step

If you do not want to remember the image id, you can tag your image by

docker tag 123456789 pavel/pavel-build

Which will tag your image as pavel/pavel-build

setting request headers in selenium

I wanted something a bit slimmer for RSpec/Ruby so that the custom code only had to live in one place. Here's my solution:

/spec/support/selenium.rb
...
RSpec.configure do |config|
  config.after(:suite) do
    $custom_headers = nil
  end
end

module RequestWithExtraHeaders
  def headers
    $custom_headers.each do |key, value|
      self.set_header "HTTP_#{key}", value
    end if $custom_headers

    super
  end
end
class ActionDispatch::Request
  prepend RequestWithExtraHeaders
end

Then in my specs:

/specs/features/something_spec.rb
...
$custom_headers = {"Referer" => referer_string}

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

Have you tried doing a full "clean" and then rebuild in Eclipse (Project->Clean...)?

Are you able to compile and run with "javac" and "java" straight from the command line? Does that work properly?

If you right click on your project, go to "Properties" and then go to "Java Build Path", are there any suspicious entries under any of the tabs? This is essentially your CLASSPATH.

In the Eclipse preferences, you may also want to double check the "Installed JREs" section in the "Java" section and make sure it matches what you think it should.

You definitely have either a stale .class file laying around somewhere or you're getting a compile-time/run-time mismatch in the versions of Java you're using.

Git diff -w ignore whitespace only at start & end of lines

For end of line use:

git diff --ignore-space-at-eol

Instead of what are you using currently:

git diff -w (--ignore-all-space)

For start of line... you are out of luck if you want a built in solution.

However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".

Failed to allocate memory: 8

In my case:

  • Using built in WXGA720 to simulate 720p device, always got this error
  • Manually set AVD resolution to 720 x 1280, works for me

hope it helps~

Cannot delete or update a parent row: a foreign key constraint fails

How about this alternative I've been using: allow the foreign key to be NULL and then choose ON DELETE SET NULL.

Personally I prefer using both "ON UPDATE CASCADE" as well as "ON DELETE SET NULL" to avoid unnecessary complications, but on your set up you may want a different approach. Also, NULL'ing foreign key values may latter lead complications as you won't know what exactly happened there. So this change should be in close relation to how your application code works.

Hope this helps.

laravel 5.5 The page has expired due to inactivity. Please refresh and try again

In my case, there was 'space' before <?php in one of my config file. This solved my issue.

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

If you are trying to

  1. Use multiple delimiters
  2. Filter any empty strings
  3. Trim leading/trailing spaces

following should work:

string str = "Tom Cruise, Scott, ,Bob | at";
IEnumerable<string> names = str
                            .Split(new char[]{',', '|'})
                            .Where(x=>x!=null && x.Trim().Length > 0)
                            .Select(x=>x.Trim());

Output

  • Tom
  • Cruise
  • Scott
  • Bob
  • at

Now you can obviously reverse the order as others suggested.

Git ignore file for Xcode projects

Best of all,

gitignore.io

Go and choose your language, and then it'll give you the file.

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

The idea is that for speed and cache considerations, operands should be read from addresses aligned to their natural size. To make this happen, the compiler pads structure members so the following member or following struct will be aligned.

struct pixel {
    unsigned char red;   // 0
    unsigned char green; // 1
    unsigned int alpha;  // 4 (gotta skip to an aligned offset)
    unsigned char blue;  // 8 (then skip 9 10 11)
};

// next offset: 12

The x86 architecture has always been able to fetch misaligned addresses. However, it's slower and when the misalignment overlaps two different cache lines, then it evicts two cache lines when an aligned access would only evict one.

Some architectures actually have to trap on misaligned reads and writes, and early versions of the ARM architecture (the one that evolved into all of today's mobile CPUs) ... well, they actually just returned bad data on for those. (They ignored the low-order bits.)

Finally, note that cache lines can be arbitrarily large, and the compiler doesn't attempt to guess at those or make a space-vs-speed tradeoff. Instead, the alignment decisions are part of the ABI and represent the minimum alignment that will eventually evenly fill up a cache line.

TL;DR: alignment is important.

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

The problem is that the true y is binary (zeros and ones), while your predictions are not. You probably generated probabilities and not predictions, hence the result :) Try instead to generate class membership, and it should work!

Setting a windows batch file variable to the day of the week

@ECHO OFF
REM GET DAY OF WEEK VIA DATE TO JULIAN DAY NUMBER CONVERSION
REM ANTONIO PEREZ AYALA
REM GET MONTH, DAY, YEAR VALUES AND ELIMINATE LEFT ZEROS
FOR /F "TOKENS=1-3 DELIMS=/" %%A IN ("%DATE%") DO SET /A MM=10%%A %% 100, DD=10%%B %% 100, YY=%%C
REM CALCULATE JULIAN DAY NUMBER, THEN DAY OF WEEK
IF %MM% LSS 3 SET /A MM+=12, YY-=1
SET /A A=YY/100, B=A/4, C=2-A+B, E=36525*(YY+4716)/100, F=306*(MM+1)/10, JDN=C+DD+E+F-1524
SET /A DOW=(JDN+1)%%7

DOW is 0 for Sunday, 1 for Monday, etc.

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

Group by month and year in MySQL

You are grouping by month only, you have to add YEAR() to the group by

Add image in title bar

You'll have to use a favicon for your page. put this in the head-tag: <link rel="shortcut icon" href="/favicon.png" type="image/png">

where favicon.png is preferably a 16x16 png image.

source: Adding a favicon to a static HTML page

Mongoose's find method with $or condition does not work properly

I solved it through googling:

var ObjectId = require('mongoose').Types.ObjectId;
var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );
// You should make string 'param' as ObjectId type. To avoid exception, 
// the 'param' must consist of more than 12 characters.

User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]}, 
  function(err,docs){
    if(!err) res.send(docs);
});

Calling onclick on a radiobutton list using javascript

The problem here is that the rendering of a RadioButtonList wraps the individual radio buttons (ListItems) in span tags and even when you assign a client-side event handler to the list item directly using Attributes it assigns the event to the span. Assigning the event to the RadioButtonList assigns it to the table it renders in.

The trick here is to add the ListItems on the aspx page and not from the code behind. You can then assign the JavaScript function to the onClick property. This blog post; attaching client-side event handler to radio button list by Juri Strumpflohner explains it all.

This only works if you know the ListItems in advance and does not help where the items in the RadioButtonList need to be dynamically added using the code behind.

JQuery Validate input file type

Simply use the .rules('add') method immediately after creating the element...

var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile

    // create the new input element
    $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" /> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");

    // declare the rule on this newly created input field        
    $('#FileUpload' + filenumber).rules('add', {
        required: true,  // <- with this you would not need 'required' attribute on input
        accept: "image/jpeg, image/pjpeg"
    });

    filenumber++; // increment counter for next time

    return false;
});
  • You'll still need to use .validate() to initialize the plugin within a DOM ready handler.

  • You'll still need to declare rules for your static elements using .validate(). Whatever input elements that are part of the form when the page loads... declare their rules within .validate().

  • You don't need to use .each(), when you're only targeting ONE element with the jQuery selector attached to .rules().

  • You don't need the required attribute on your input element when you're declaring the required rule using .validate() or .rules('add'). For whatever reason, if you still want the HTML5 attribute, at least use a proper format like required="required".

Working DEMO: http://jsfiddle.net/8dAU8/5/

Effective way to find any file's Encoding

Check this.

UDE

This is a port of Mozilla Universal Charset Detector and you can use it like this...

public static void Main(String[] args)
{
    string filename = args[0];
    using (FileStream fs = File.OpenRead(filename)) {
        Ude.CharsetDetector cdet = new Ude.CharsetDetector();
        cdet.Feed(fs);
        cdet.DataEnd();
        if (cdet.Charset != null) {
            Console.WriteLine("Charset: {0}, confidence: {1}", 
                 cdet.Charset, cdet.Confidence);
        } else {
            Console.WriteLine("Detection failed.");
        }
    }
}

MySQL - SELECT all columns WHERE one column is DISTINCT

What you want is the following:

SELECT DISTINCT * FROM posted WHERE ad='$key' GROUP BY link ORDER BY day, month

if there are 4 rows for example where link is the same, it will pick only one (I asume the first one).

Best way to get the max value in a Spark dataframe column

In case some wonders how to do it using Scala (using Spark 2.0.+), here you go:

scala> df.createOrReplaceTempView("TEMP_DF")
scala> val myMax = spark.sql("SELECT MAX(x) as maxval FROM TEMP_DF").
    collect()(0).getInt(0)
scala> print(myMax)
117

Reading an integer from user input

int op = 0;
string in = string.Empty;
do
{
    Console.WriteLine("enter choice");
    in = Console.ReadLine();
} while (!int.TryParse(in, out op));

Is there a job scheduler library for node.js?

later.js is a pretty good JavaScript "scheduler" library. Can run on Node.js or in a web browser.

Rails server says port already used, how to kill that process?

You need to get process id of program using tcp port 3000. To get process id

lsof -i tcp:3000 -t

And then using that process id, simply kill process using ubuntu kill command.

kill -9 pid

Or just run below mentioned combine command. It will first fetch pid and then kill that process.

kill -9 $(lsof -i tcp:3000 -t)

Post parameter is always null

I am pretty late to this but was having similar issues and after a day of going through a lot of the answers here and getting background I have found the easiest/lightweight solution to pass back one or more parameters to a Web API 2 Action is as follows:

This assumes that you know how to setup a Web API controller/action with correct routing, if not refer to: https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api.

First the Controller Action, this solution also requires the Newtonsoft.Json library.

[HttpPost]
public string PostProcessData([FromBody]string parameters) {
    if (!String.IsNullOrEmpty(parameters)) {
        JObject json = JObject.Parse(parameters);

        // Code logic below
        // Can access params via json["paramName"].ToString();
    }
    return "";
}

Client Side using jQuery

var dataToSend = JSON.stringify({ param1: "value1", param2: "value2"...});
$.post('/Web_API_URI', { '': dataToSend }).done(function (data) {
     console.debug(data); // returned data from Web API
 });

The key issue I found was making sure you only send a single overall parameter back to the Web API and make sure it has no name just the value { '': dataToSend }otherwise your value will be null on the server side.

With this you can send one or many parameters to the Web API in a JSON structure and you don't need to declare any extra objects server side to handle complex data. The JObject also allows you to dynamically iterate over all parameters passed in allowing easier scalability should your parameters change over time. Hopefully that helps someone out that was struggling like me.

Using ZXing to create an Android barcode scanning app

Using Zxing this way requires a user to also install the barcode scanner app, which isn't ideal. What you probably want is to bundle Zxing into your app directly.

I highly recommend using this library: https://github.com/dm77/barcodescanner

It takes all the crazy build issues you're going to run into trying to integrate Xzing or Zbar directly. It uses those libraries under the covers, but wraps them in a very simple to use API.

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

class Program
{
    static void Main(string[] args)
    {

        int transactionDate = 20201010;
        int? transactionTime = 210000;

        var agreementDate = DateTime.Today;
        var previousDate = agreementDate.AddDays(-1);

        var agreementHour = 22;
        var agreementMinute = 0;
        var agreementSecond = 0;

        var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
        var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);

        DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));

        Console.WriteLine("Selected Date : " + selectedDate.ToString());
        Console.WriteLine("Start Date : " + startDate.ToString());
        Console.WriteLine("End Date : " + endDate.ToString());

        if (selectedDate > startDate && selectedDate <= endDate)
            Console.WriteLine("Between two dates..");
        else if (selectedDate <= startDate)
            Console.WriteLine("Less than or equal to the start date!");
        else if (selectedDate > endDate)
            Console.WriteLine("Greater than end date!");
        else
            Console.WriteLine("Out of date ranges!");
    }
}

File.Move Does Not Work - File Already Exists

1) With C# on .Net Core 3.0 and beyond, there is now a third boolean parameter:

see https://docs.microsoft.com/en-us/dotnet/api/system.io.file.move?view=netcore-3.1

In .NET Core 3.0 and later versions, you can call Move(String, String, Boolean) setting the parameter overwrite to true, which will replace the file if it exists.

2) For all other versions of .Net, https://stackoverflow.com/a/42224803/887092 is the best answer. Copy with Overwrite, then delete the source file. This is better because it makes it an atomic operation. (I have attempted to update the MS Docs with this)

Difference between const reference and normal parameter

The important difference is that when passing by const reference, no new object is created. In the function body, the parameter is effectively an alias for the object passed in.

Because the reference is a const reference the function body cannot directly change the value of that object. This has a similar property to passing by value where the function body also cannot change the value of the object that was passed in, in this case because the parameter is a copy.

There are crucial differences. If the parameter is a const reference, but the object passed it was not in fact const then the value of the object may be changed during the function call itself.

E.g.

int a;

void DoWork(const int &n)
{
    a = n * 2;  // If n was a reference to a, n will have been doubled 

    f();  // Might change the value of whatever n refers to 
}

int main()
{
    DoWork(a);
}

Also if the object passed in was not actually const then the function could (even if it is ill advised) change its value with a cast.

e.g.

void DoWork(const int &n)
{
    const_cast<int&>(n) = 22;
}

This would cause undefined behaviour if the object passed in was actually const.

When the parameter is passed by const reference, extra costs include dereferencing, worse object locality, fewer opportunities for compile optimizing.

When the parameter is passed by value and extra cost is the need to create a parameter copy. Typically this is only of concern when the object type is large.

Initializing a member array in constructor initializer

You want to init an array of ints in your constructor? Point it to a static array.

class C 
{
public:
    int *cArray;

};

C::C {
    static int c_init[]{1,2,3};
    cArray = c_init;
}

Mask output of `The following objects are masked from....:` after calling attach() function

It may be "better" to not use attach at all. On the plus side, you can save some typing if you use attach. Let's say your dataset is called mydata and you have variables called v1, v2, and v3. If you don't attach mydata, then you will type mean(mydata$v1) to get the mean of v1. If you do attach mydata, then you will type mean(v1) to get the mean of v1. But, if you don't detach the mydata dataset (every time), you'll get the message about the objects being masked going forward.

Solution 1 (assuming you want to attach):

  1. Use detach every time.
  2. See Dan Tarr's response if you already have the data attached (and it may be in the global environment several times). Then, in the future, use detach every time.

Solution 2

Don't use attach. Instead, include the dataset name every time you refer to a variable. The form is mydata$v1 (name of data set, dollar sign, name of variable).

As for me, I used solution 1 a lot in the past, but I've moved to solution 2. It's a bit more typing in the beginning, but if you are going to use the code multiple times, it just seems cleaner.

How to list only top level directories in Python?

Filter the result using os.path.isdir() (and use os.path.join() to get the real path):

>>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']

How can I search for a multiline pattern in a file?

You can use the grep alternative sift here (disclaimer: I am the author).

It support multiline matching and limiting the search to specific file types out of the box:

sift -m --files '*.py' 'YOUR_PATTERN'

(search all *.py files for the specified multiline regex pattern)

It is available for all major operating systems. Take a look at the samples page to see how it can be used to to extract multiline values from an XML file.

How to download a branch with git?

Thanks to a related question, I found out that I need to "checkout" the remote branch as a new local branch, and specify a new local branch name.

git checkout -b newlocalbranchname origin/branch-name

Or you can do:

git checkout -t origin/branch-name

The latter will create a branch that is also set to track the remote branch.


Update: It's been 5 years since I originally posted this question. I've learned a lot and git has improved since then. My usual workflow is a little different now.

If I want to fetch the remote branches, I simply run:

git pull

This will fetch all of the remote branches and merge the current branch. It will display an output that looks something like this:

From github.com:andrewhavens/example-project
   dbd07ad..4316d29  master     -> origin/master
 * [new branch]      production -> origin/production
 * [new branch]      my-bugfix-branch -> origin/my-bugfix-branch
First, rewinding head to replay your work on top of it...
Fast-forwarded master to 4316d296c55ac2e13992a22161fc327944bcf5b8.

Now git knows about my new my-bugfix-branch. To switch to this branch, I can simply run:

git checkout my-bugfix-branch

Normally, I would need to create the branch before I could check it out, but in newer versions of git, it's smart enough to know that you want to checkout a local copy of this remote branch.

sql: check if entry in table A exists in table B

This also works

SELECT *
FROM tableB
WHERE ID NOT IN (
  SELECT ID FROM tableA
);

How to Set Opacity (Alpha) for View in Android

For a view you can set opacity by the following.

view_name.setAlpha(float_value);

The property view.setAlpha(int) is deprecated for the API version greater than 11. Henceforth, property like .setAlpha(0.5f) is used.

Correct way to delete cookies server-side

At the time of my writing this answer, the accepted answer to this question appears to state that browsers are not required to delete a cookie when receiving a replacement cookie whose Expires value is in the past. That claim is false. Setting Expires to be in the past is the standard, spec-compliant way of deleting a cookie, and user agents are required by spec to respect it.

Using an Expires attribute in the past to delete a cookie is correct and is the way to remove cookies dictated by the spec. The examples section of RFC 6255 states:

Finally, to remove a cookie, the server returns a Set-Cookie header with an expiration date in the past. The server will be successful in removing the cookie only if the Path and the Domain attribute in the Set-Cookie header match the values used when the cookie was created.

The User Agent Requirements section includes the following requirements, which together have the effect that a cookie must be immediately expunged if the user agent receives a new cookie with the same name whose expiry date is in the past

  1. If [when receiving a new cookie] the cookie store contains a cookie with the same name, domain, and path as the newly created cookie:

    1. ...
    2. ...
    3. Update the creation-time of the newly created cookie to match the creation-time of the old-cookie.
    4. Remove the old-cookie from the cookie store.
  2. Insert the newly created cookie into the cookie store.

A cookie is "expired" if the cookie has an expiry date in the past.

The user agent MUST evict all expired cookies from the cookie store if, at any time, an expired cookie exists in the cookie store.

Points 11-3, 11-4, and 12 above together mean that when a new cookie is received with the same name, domain, and path, the old cookie must be expunged and replaced with the new cookie. Finally, the point below about expired cookies further dictates that after that is done, the new cookie must also be immediately evicted. The spec offers no wiggle room to browsers on this point; if a browser were to offer the user the option to disable cookie expiration, as the accepted answer suggests some browsers do, then it would be in violation of the spec. (Such a feature would also have little use, and as far as I know it does not exist in any browser.)

Why, then, did the OP of this question observe this approach failing? Though I have not dusted off a copy of Internet Explorer to check its behaviour, I suspect it was because the OP's Expires value was malformed! They used this value:

expires=Thu, Jan 01 1970 00:00:00 UTC;

However, this is syntactically invalid in two ways.

The syntax section of the spec dictates that the value of the Expires attribute must be a

rfc1123-date, defined in [RFC2616], Section 3.3.1

Following the second link above, we find this given as an example of the format:

Sun, 06 Nov 1994 08:49:37 GMT

and find that the syntax definition...

  1. requires that dates be written in day month year format, not month day year format as used by the question asker.

    Specifically, it defines rfc1123-date as follows:

    rfc1123-date = wkday "," SP date1 SP time SP "GMT"
    

    and defines date1 like this:

    date1        = 2DIGIT SP month SP 4DIGIT
                 ; day month year (e.g., 02 Jun 1982)
    

and

  1. doesn't permit UTC as a timezone.

    The spec contains the following statement about what timezone offsets are acceptable in this format:

    All HTTP date/time stamps MUST be represented in Greenwich Mean Time (GMT), without exception.

    What's more if we dig deeper into the original spec of this datetime format, we find that in its initial spec in https://tools.ietf.org/html/rfc822, the Syntax section lists "UT" (meaning "universal time") as a possible value, but does not list not UTC (Coordinated Universal Time) as valid. As far as I know, using "UTC" in this date format has never been valid; it wasn't a valid value when the format was first specified in 1982, and the HTTP spec has adopted a strictly more restrictive version of the format by banning the use of all "zone" values other than "GMT".

If the question asker here had instead used an Expires attribute like this, then:

expires=Thu, 01 Jan 1970 00:00:00 GMT;

then it would presumably have worked.

How to add Tomcat Server in eclipse

  1. Go to Server tab enter image description here

  2. Click on No servers are available. Click this link to create a new server.

  3. Select Tomcat V8.0 from server type list: enter image description here

  4. Provide path of server: enter image description here

  5. Click Finish.

  6. You will see server added: enter image description here

  7. Right click->Start

Now you can run your web applications on server.

INSERT IF NOT EXISTS ELSE UPDATE?

You should use the INSERT OR IGNORE command followed by an UPDATE command: In the following example name is a primary key:

INSERT OR IGNORE INTO my_table (name, age) VALUES ('Karen', 34)
UPDATE my_table SET age = 34 WHERE name='Karen'

The first command will insert the record. If the record exists, it will ignore the error caused by the conflict with an existing primary key.

The second command will update the record (which now definitely exists)

How can I create an utility class?

Making a class abstract sends a message to the readers of your code that you want users of your abstract class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.

Therefore, adding a private constructor is a better choice here. You should also make the class final to disallow subclassing of your utility class.

How to subtract a day from a date?

You can use a timedelta object:

from datetime import datetime, timedelta
    
d = datetime.today() - timedelta(days=days_to_subtract)

How do I search an SQL Server database for a string?

You could;

  1. Script the database to a single file and search the file for tblEmployees using a text editor. In SQL Server Management Studio (SSMS), right click over the database and choose Generate Scripts.
  2. Use SSMS 'View Dependencies' by right clicking over tblEmployees to see which other objects are dependent on it
  3. Use a free third-party tool such as Redgate Software's SQL Search to search all database objects by name and content by keyword.

when exactly are we supposed to use "public static final String"?

The keyword final means that the value is constant(it cannot be changed). It is analogous to const in C.

And you can treat static as a global variable which has scope. It basically means if you change it for one object it will be changed for all just like a global variable(limited by scope).

Hope it helps.

Cannot execute script: Insufficient memory to continue the execution of the program

For Windows Authentication use this sql cmd

SQLCMD -S TestSQLServer\SQLEXPRESS  -d AdventureWorks2018 -i "d:\document\sql document\script.sql"

Note: If there is any space in the sql file path then use " (Quotation marks) "

For SQL Server Authentication use this sql cmd

SQLCMD -S TestSQLServer\SQLEXPRESS -U sa -P sasa  -d AdventureWorks2018 -i "d:\document\sql document\script.sql"

-S TestSQLServer\SQLEXPRESS: Here specify SQL Server Name

-U sa: Username (in case of SQL Server Authentication)

-P sasa: Password (in case of SQL Server Authentication)

-d AdventureWorks2018: Database Name come here

-i "d:\document\sql document\script.sql": File Path of SQLFile

Wait until ActiveWorkbook.RefreshAll finishes - VBA

This worked for me:

ActiveWorkbook.refreshall
ActiveWorkbook.Save

When you save the workbook it's necessary to complete the refresh.

How do I update zsh to the latest version?

As far as I'm aware, you've got three options to install zsh on Mac OS X:

  • Pre-built binary. The only one I know of is the one that ships with OS X; this is probably what you're running now.
  • Use a package system (Ports, Homebrew).
  • Install from source. Last time I did this it wasn't too difficult (./configure, make, make install).

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

if you have remote server installed on you machine. give server.py host as "localhost" and the port number. then client side , you have to give local ip- 127.0.0.1 and port number. then its works

Breadth First Vs Depth First

Understanding the terms:

This picture should give you the idea about the context in which the words breadth and depth are used.

Understanding Breadth and Depth


Depth-First Search:

Depth-First Search

  • Depth-first search algorithm acts as if it wants to get as far away from the starting point as quickly as possible.

  • It generally uses a Stack to remember where it should go when it reaches a dead end.

  • Rules to follow: Push first vertex A on to the Stack

    1. If possible, visit an adjacent unvisited vertex, mark it as visited, and push it on the stack.
    2. If you can’t follow Rule 1, then, if possible, pop a vertex off the stack.
    3. If you can’t follow Rule 1 or Rule 2, you’re done.
  • Java code:

    public void searchDepthFirst() {
        // Begin at vertex 0 (A)
        vertexList[0].wasVisited = true;
        displayVertex(0);
        stack.push(0);
        while (!stack.isEmpty()) {
            int adjacentVertex = getAdjacentUnvisitedVertex(stack.peek());
            // If no such vertex
            if (adjacentVertex == -1) {
                stack.pop();
            } else {
                vertexList[adjacentVertex].wasVisited = true;
                // Do something
                stack.push(adjacentVertex);
            }
        }
        // Stack is empty, so we're done, reset flags
        for (int j = 0; j < nVerts; j++)
            vertexList[j].wasVisited = false;
    }
    
  • Applications: Depth-first searches are often used in simulations of games (and game-like situations in the real world). In a typical game you can choose one of several possible actions. Each choice leads to further choices, each of which leads to further choices, and so on into an ever-expanding tree-shaped graph of possibilities.


Breadth-First Search:

Breadth-First Search

  • The breadth-first search algorithm likes to stay as close as possible to the starting point.
  • This kind of search is generally implemented using a Queue.
  • Rules to follow: Make starting Vertex A the current vertex
    1. Visit the next unvisited vertex (if there is one) that’s adjacent to the current vertex, mark it, and insert it into the queue.
    2. If you can’t carry out Rule 1 because there are no more unvisited vertices, remove a vertex from the queue (if possible) and make it the current vertex.
    3. If you can’t carry out Rule 2 because the queue is empty, you’re done.
  • Java code:

    public void searchBreadthFirst() {
        vertexList[0].wasVisited = true;
        displayVertex(0);
        queue.insert(0);
        int v2;
        while (!queue.isEmpty()) {
            int v1 = queue.remove();
            // Until it has no unvisited neighbors, get one
            while ((v2 = getAdjUnvisitedVertex(v1)) != -1) {
                vertexList[v2].wasVisited = true;
                // Do something
                queue.insert(v2);
            }
        }
        // Queue is empty, so we're done, reset flags
        for (int j = 0; j < nVerts; j++) 
            vertexList[j].wasVisited = false;
    }
    
  • Applications: Breadth-first search first finds all the vertices that are one edge away from the starting point, then all the vertices that are two edges away, and so on. This is useful if you’re trying to find the shortest path from the starting vertex to a given vertex.

Hopefully that should be enough for understanding the Breadth-First and Depth-First searches. For further reading I would recommend the Graphs chapter from an excellent data structures book by Robert Lafore.

Spark - SELECT WHERE or filtering?

As Yaron mentioned, there isn't any difference between where and filter.

filter is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.

filter overloaded method

We can use explain() to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name and person_country columns. All of the following code snippets will return the same Physical Plan below:

df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()

These all return this Physical Plan:

== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
   +- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>

The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.

Apply .gitignore on an existing repository already tracking large number of files

Use git clean
Get help on this running

git clean -h

If you want to see what would happen first, make sure to pass the -n switch for a dry run:

git clean -xn

To remove gitingnored garbage

git clean -xdf

Careful: You may be ignoring local config files like database.yml which would also be removed. Use at your own risk.

Then

git add .
git commit -m ".gitignore is now working"
git push

Append an int to a std::string

You cannot cast an int to a char* to get a string. Try this:

std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();

stringstream reference

How to filter in NaN (pandas)?

Simplest of all solutions:

filtered_df = df[df['var2'].isnull()]

This filters and gives you rows which has only NaN values in 'var2' column.

Original purpose of <input type="hidden">?

The values of form elements including type='hidden' are submitted to the server when the form is posted. input type="hidden" values are not visible in the page. Maintaining User IDs in hidden fields, for example, is one of the many uses.

SO uses a hidden field for the upvote click.

<input value="16293741" name="postId" type="hidden">

Using this value, the server-side script can store the upvote.

How to select clear table contents without destroying the table?

I reworked Doug Glancy's solution to avoid rows deletion, which can lead to #Ref issue in formulae.

Sub ListReset(lst As ListObject)
'clears a listObject while leaving row 1 empty, with formulae
    With lst
        If .ShowAutoFilter Then .AutoFilter.ShowAllData
        On Error Resume Next
        With .DataBodyRange
            .Offset(1).Rows.Clear
            .Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
        End With
        On Error GoTo 0
        .Resize .Range.Rows("1:2")
    End With
End Sub

How to use ESLint with Jest

In your .eslintignore file add the following value:

**/__tests__/

This should ignore all instances of the __tests__ directory and their children.

How to present a simple alert message in java?

If you don't like "verbosity" you can always wrap your code in a short method:

private void msgbox(String s){
   JOptionPane.showMessageDialog(null, s);
}

and the usage:

msgbox("don't touch that!");

Count distinct value pairs in multiple columns in SQL

Another (probably not production-ready or recommended) method I just came up with is to concat the values to a string and count this string distinctively:

SELECT count(DISTINCT concat(id, name, address)) FROM mytable;

How to add spacing between UITableViewCell

I think this is the cleanest solution:

class MyTableViewCell: UITableViewCell {
    override func awakeFromNib() {
        super.awakeFromNib()
        layoutMargins = UIEdgeInsetsMake(8, 0, 8, 0)
    }
}

Sending POST parameters with Postman doesn't work, but sending GET parameters does

Sorry if this is thread Necromancy, but this is still relevant today, especially with how much APIs are used!

An issue I had was: I didn't know that under the 'Key' column you need to put: 'Content-Type'; I thought this was a User Key for when it came back in the request, which it isn't.

So something as simple as that may help you, I think Postman could word that column better, because I didn't even have to read the Documentation when it came to using Fiddler; whereas I did with Postman.

Postman picture

How to install libusb in Ubuntu

you can creat symlink to your libusb after locate it in your system :

sudo ln -s /lib/x86_64-linux-gnu/libusb-1.0.so.0 /usr/lib/libusbx-1.0.so.0.1.0 

sudo ln -s /lib/x86_64-linux-gnu/libusb-1.0.so.0 /usr/lib/libusbx-1.0.so

CSS file not refreshing in browser

I always use Ctrl+Shift+F5 out of habit, it should force a full-refresh including by-passing any http proxies you may be going through.

Cannot make file java.io.IOException: No such file or directory

I got the same problem when using rest-easy. After searching while i figured that this error occured when there is no place to keep temporary files. So in tomcat you can just create tomcat-root/temp folder.

Resource u'tokenizers/punkt/english.pickle' not found

Just make sure you are using Jupyter Notebook and in a notebook, do the following:

import nltk

nltk.download()

Then one popup window will appear (showing info https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml) From that you have to download everything.

Then rerun your code.

How to use CMAKE_INSTALL_PREFIX

That should be (see the docs):

cmake -DCMAKE_INSTALL_PREFIX=/usr ..

How to call getResources() from a class which has no context?

Example: Getting app_name string:

Resources.getSystem().getString( R.string.app_name )

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

Try this:

package my_default;

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

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

public class Test {

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

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

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

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


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

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

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

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

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

        return sheet;
    }

}

Comparing arrays for equality in C++

When we use an array, we are really using a pointer to the first element in the array. Hence, this condition if( iar1 == iar2 ) actually compares two addresses. Those pointers do not address the same object.

oracle sql: update if exists else insert

You could use the SQL%ROWCOUNT Oracle variable:

UPDATE table1
  SET field2 = value2, 
      field3 = value3 
WHERE field1 = value1; 

IF (SQL%ROWCOUNT = 0) THEN 

  INSERT INTO table (field1, field2, field3)
  VALUES (value1, value2, value3);

END IF; 

It would be easier just to determine if your primary key (i.e. field1) has a value and then perform an insert or update accordingly. That is, if you use said values as parameters for a stored procedure.

How to semantically add heading to a list

You could also use the <figure> element to link a heading to your list like this:

<figure>
    <figcaption>My favorite fruits</figcaption>    
       <ul>
          <li>Banana</li>
          <li>Orange</li>
          <li>Chocolate</li>
       </ul>
</figure>

Source: https://www.w3.org/TR/2017/WD-html53-20171214/single-page.html#the-li-element (Example 162)

Setting the number of map tasks and reduce tasks

In the newer version of Hadoop, there are much more granular mapreduce.job.running.map.limit and mapreduce.job.running.reduce.limit which allows you to set the mapper and reducer count irrespective of hdfs file split size. This is helpful if you are under constraint to not take up large resources in the cluster.

JIRA

How to get height of Keyboard?

I uses below code,

override func viewDidLoad() {
    super.viewDidLoad()
    self.registerObservers()
}

func registerObservers(){

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

@objc func keyboardWillAppear(notification: Notification){
    if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
        self.view.transform = CGAffineTransform(translationX: 0, y: -keyboardHeight)
    }
}

@objc func keyboardWillHide(notification: Notification){
        self.view.transform = .identity
}

How can I run a function from a script in command line?

Well, while the other answers are right - you can certainly do something else: if you have access to the bash script, you can modify it, and simply place at the end the special parameter "$@" - which will expand to the arguments of the command line you specify, and since it's "alone" the shell will try to call them verbatim; and here you could specify the function name as the first argument. Example:

$ cat test.sh
testA() {
  echo "TEST A $1";
}

testB() {
  echo "TEST B $2";
}

"$@"


$ bash test.sh
$ bash test.sh testA
TEST A 
$ bash test.sh testA arg1 arg2
TEST A arg1
$ bash test.sh testB arg1 arg2
TEST B arg2

For polish, you can first verify that the command exists and is a function:

# Check if the function exists (bash specific)
if declare -f "$1" > /dev/null
then
  # call arguments verbatim
  "$@"
else
  # Show a helpful error
  echo "'$1' is not a known function name" >&2
  exit 1
fi

Difference between document.addEventListener and window.addEventListener?

The window binding refers to a built-in object provided by the browser. It represents the browser window that contains the document. Calling its addEventListener method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.

<p>Some paragraph.</p>
<script>
  window.addEventListener("click", () => {
    console.log("Test");
  });
</script>

Following points should be noted before select window or document to addEventListners

  1. Most of the events are same for window or document but some events like resize, and other events related to loading, unloading, and opening/closing should all be set on the window.
  2. Since window has the document it is good practice to use document to handle (if it can handle) since event will hit document first.
  3. Internet Explorer doesn't respond to many events registered on the window,so you will need to use document for registering event.

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

How can I use a local image as the base image with a dockerfile?

You can use it without doing anything special. If you have a local image called blah you can do FROM blah. If you do FROM blah in your Dockerfile, but don't have a local image called blah, then Docker will try to pull it from the registry.

In other words, if a Dockerfile does FROM ubuntu, but you have a local image called ubuntu different from the official one, your image will override it.

Why is this printing 'None' in the output?

Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.

Use return statement at end of function to return value.

e.g.:

Return None value.

>>> def test1():
...    print "In function."
... 
>>> a = test1()
In function.
>>> print a
None
>>> 
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>> 

Use return statement

>>> def test():
...   return "ACV"
... 
>>> print test()
ACV
>>> 
>>> a = test()
>>> print a
ACV
>>> 

Trusting all certificates with okHttp

Following method is deprecated

sslSocketFactory(SSLSocketFactory sslSocketFactory)

Consider updating it to

sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)

How to add elements to an empty array in PHP?

You can use array_push. It adds the elements to the end of the array, like in a stack.

You could have also done it like this:

$cart = array(13, "foo", $obj);

Forbidden :You don't have permission to access /phpmyadmin on this server

You could simply go to phpmyadmin.conf file and change "deny from all" to "allow from all". Well it worked for me, hope it works for you as well.

In a javascript array, how do I get the last 5 elements, excluding the first element?

Try this:

var array = [1, 55, 77, 88, 76, 59];
var array_last_five;
array_last_five = array.slice(-5);
if (array.length < 6) {
     array_last_five.shift();
}

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

I have a slightly different perspective on the difference between a DATETIME and a TIMESTAMP. A DATETIME stores a literal value of a date and time with no reference to any particular timezone. So, I can set a DATETIME column to a value such as '2019-01-16 12:15:00' to indicate precisely when my last birthday occurred. Was this Eastern Standard Time? Pacific Standard Time? Who knows? Where the current session time zone of the server comes into play occurs when you set a DATETIME column to some value such as NOW(). The value stored will be the current date and time using the current session time zone in effect. But once a DATETIME column has been set, it will display the same regardless of what the current session time zone is.

A TIMESTAMP column on the other hand takes the '2019-01-16 12:15:00' value you are setting into it and interprets it in the current session time zone to compute an internal representation relative to 1/1/1970 00:00:00 UTC. When the column is displayed, it will be converted back for display based on whatever the current session time zone is. It's a useful fiction to think of a TIMESTAMP as taking the value you are setting and converting it from the current session time zone to UTC for storing and then converting it back to the current session time zone for displaying.

If my server is in San Francisco but I am running an event in New York that starts on 9/1/1029 at 20:00, I would use a TIMESTAMP column for holding the start time, set the session time zone to 'America/New York' and set the start time to '2009-09-01 20:00:00'. If I want to know whether the event has occurred or not, regardless of the current session time zone setting I can compare the start time with NOW(). Of course, for displaying in a meaningful way to a perspective customer, I would need to set the correct session time zone. If I did not need to do time comparisons, then I would probably be better off just using a DATETIME column, which will display correctly (with an implied EST time zone) regardless of what the current session time zone is.

TIMESTAMP LIMITATION

The TIMESTAMP type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC and so it may not usable for your particular application. In that case you will have to use a DATETIME type. You will, of course, always have to be concerned that the current session time zone is set properly whenever you are using this type with date functions such as NOW().

jQuery, get html of a whole element

You can easily get child itself and all of its decedents (children) with Jquery's Clone() method, just

var child = $('#div div:nth-child(1)').clone();  

var child2 = $('#div div:nth-child(2)').clone();

You will get this for first query as asked in question

<div id="div1">
     <p>Some Content</p>
</div>

What does numpy.random.seed(0) do?

There is a nice explanation in Numpy docs: https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.RandomState.html it refers to Mersenne Twister pseudo-random number generator. More details on the algorithm here: https://en.wikipedia.org/wiki/Mersenne_Twister

array_push() with key value pair

$data['cat'] = 'wagon';

That's all you need to add the key and value to the array.

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

Building on Oded's answer, you could also set the default option but not make it a selectable option if it's just dummy text. For example you could do:

<option selected="selected" disabled="disabled">Select a language</option>

This would show "Select a language" before the user clicks the select box but the user wouldn't be able to select it because of the disabled attribute.

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

Are iframes considered 'bad practice'?

There are definitely uses for iframes folks. How else would you put the weather networks widget on your page? The only other way is to grab their XML and parse it, but then of course you need conditions to throw up the pertenant weather graphics... not really worth it, but way cleaner if you have the time.

What is the difference between require() and library()?

Another benefit of require() is that it returns a logical value by default. TRUE if the packages is loaded, FALSE if it isn't.

> test <- library("abc")
Error in library("abc") : there is no package called 'abc'
> test
Error: object 'test' not found
> test <- require("abc")
Loading required package: abc
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called 'abc'
> test
[1] FALSE

So you can use require() in constructions like the one below. Which mainly handy if you want to distribute your code to our R installation were packages might not be installed.

if(require("lme4")){
    print("lme4 is loaded correctly")
} else {
    print("trying to install lme4")
    install.packages("lme4")
    if(require(lme4)){
        print("lme4 installed and loaded")
    } else {
        stop("could not install lme4")
    }
}

Node.js on multi-core machines

Future version of node will allow you to fork a process and pass messages to it and Ryan has stated he wants to find some way to also share file handlers, so it won't be a straight forward Web Worker implementation.

At this time there is not an easy solution for this but it's still very early and node is one of the fastest moving open source projects I've ever seen so expect something awesome in the near future.

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

#!/bin/bash
ipcs -m | grep `whoami` | awk '{ print $2 }' | xargs -n1 ipcrm -m
ipcs -s | grep `whoami` | awk '{ print $2 }' | xargs -n1 ipcrm -s
ipcs -q | grep `whoami` | awk '{ print $2 }' | xargs -n1 ipcrm -q

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Compiler error: memset was not declared in this scope

You should include <string.h> (or its C++ equivalent, <cstring>).

How do I autoindent in Netbeans?

To format all the code in NetBeans, press Alt + Shift + F. If you want to indent lines, select the lines and press Alt + Shift + right arrow key, and to unindent, press Alt + Shift + left arrow key.

How to shift a column in Pandas DataFrame

If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:

    offset = 5
    DF = DF.append([np.nan for x in range(offset)])
    DF = DF.shift(periods=offset)
    DF = DF.reset_index() #Only works if sequential index

In angular $http service, How can I catch the "status" of error?

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. Have a look at the docs https://docs.angularjs.org/api/ng/service/$http

Now the right way to use is:

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

The response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

A response status code between 200 and 299 is considered a success status and will result in the success callback being called.

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

Try this if you want to display one of duplicate rows based on RequestID and CreatedDate and show the latest HistoryStatus.

with t as (select row_number()over(partition by RequestID,CreatedDate order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t a where  rnum in (SELECT Max(rnum) FROM t GROUP BY RequestID,CreatedDate having t.RequestID=a.RequestID)

or if you want to select one of duplicate rows considering CreatedDate only and show the latest HistoryStatus then try the query below.

with t as (select row_number()over(partition by CreatedDate order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t  where  rnum = (SELECT Max(rnum) FROM t)

Or if you want to select one of duplicate rows considering Request ID only and show the latest HistoryStatus then use the query below

with t as (select row_number()over(partition by RequestID order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t a where  rnum in (SELECT Max(rnum) FROM t GROUP BY RequestID,CreatedDate having t.RequestID=a.RequestID)

All the above queries I have written in sql server 2005.

pod install -bash: pod: command not found

Installing CocoaPods on OS X 10.11

These instructions were tested on all betas and the final release of El Capitan.

Custom GEM_HOME

This is the solution when you are receiving above error

$ mkdir -p $HOME/Software/ruby
$ export GEM_HOME=$HOME/Software/ruby
$ gem install cocoapods
[...]
1 gem installed
$ export PATH=$PATH:$HOME/Software/ruby/bin
$ pod --version
0.38.2

redirect to current page in ASP.Net

http://en.wikipedia.org/wiki/Post/Redirect/Get

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

PostgreSQL database service

(start -> run -> services.msc) and look for the postgresql-[version] service then right click and enable it

How to reposition Chrome Developer Tools

In addition, if you want to see Sources and Console on one window, go to:

"Customize and control DevTools -> "Show console drawer"

You can also see it here at the right corner:

"Show console drawer"

How to append a newline to StringBuilder

Another option is to use Apache Commons StrBuilder, which has the functionality that's lacking in StringBuilder.

StrBuilder.appendLn()

As of version 3.6 StrBuilder has been deprecated in favour of TextStringBuilder which has the same functionality

How to add a footer to the UITableView?

These samples work well. You can check section and then return a height to show or hide section. Don't forget to extend your viewcontroller from UITableViewDelegate.

Objective-C

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0)
    {
        // to hide footer for section 0 
        return 0.0;
    }
    else
    {
        // show footer for every section except section 0 
        return HEIGHT_YOU_WANT;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor = [UIColor blackColor];
    return footerView;
}

Swift

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = UIView()
    footerView.backgroundColor = UIColor.black
    return footerView
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    if section == 0 {
        // to hide footer for section 0
        return 0.0
    } else {
        // show footer for every section except section 0
        return HEIGHT_YOU_WANT
    }
}

SOAP or REST for Web Services?

Most of the applications I write are server-side C# or Java, or desktop applications in WinForms or WPF. These applications tend to need a richer service API than REST can provide. Plus, I don't want to spend any more than a couple minutes creating my web service client. The WSDL processing client generation tools allow me to implement my client and move on to adding business value.

Now, if I were writing a web service explicitly for some javascript ajax calls, it'd probably be in REST; just for the sake knowing the client technology and leveraging JSON. In my opinion, web service APIs used from javascript probably shouldn't be very complex, as that type of complexity seems to be better handled server-side.

With that said, there some SOAP clients for javascript; I know jQuery has one. Thus, SOAP can be leveraged from javascript; just not as nicely as a REST service returning JSON strings. So if I had a web service that I wanted to be complex enough that it was flexible for an arbitrary number of client technologies and uses, I'd go with SOAP.

Mismatched anonymous define() module

Per the docs:

If you manually code a script tag in HTML to load a script with an anonymous define() call, this error can occur.

Also seen if you manually code a script tag in HTML to load a script that has a few named modules, but then try to load an anonymous module that ends up having the same name as one of the named modules in the script loaded by the manually coded script tag.

Finally, if you use the loader plugins or anonymous modules (modules that call define() with no string ID) but do not use the RequireJS optimizer to combine files together, this error can occur. The optimizer knows how to name anonymous modules correctly so that they can be combined with other modules in an optimized file.

To avoid the error:

  • Be sure to load all scripts that call define() via the RequireJS API. Do not manually code script tags in HTML to load scripts that have define() calls in them.

  • If you manually code an HTML script tag, be sure it only includes named modules, and that an anonymous module that will have the same name as one of the modules in that file is not loaded.

  • If the problem is the use of loader plugins or anonymous modules but the RequireJS optimizer is not used for file bundling, use the RequireJS optimizer.

How to make <div> fill <td> height

Modify the background image of the <td> itself.

Or apply some css to the div:

.thatSetsABackgroundWithAnIcon{
    height:100%;
}

Return value in a Bash function

As an add-on to others' excellent posts, here's an article summarizing these techniques:

  • set a global variable
  • set a global variable, whose name you passed to the function
  • set the return code (and pick it up with $?)
  • 'echo' some data (and pick it up with MYVAR=$(myfunction) )

Returning Values from Bash Functions

Cannot add a project to a Tomcat server in Eclipse

  1. Right-click on project
  2. Go to properties => project factes
  3. Click on runtime tab
  4. Check the box of the server
  5. Then ok

Close the eclipse and start the server you will able to see and run the project.

Sharing link on WhatsApp from mobile website (not application) for Android

Use: https://wa.me/1XXXXXXXXXX

Don't use: https://wa.me/+001-(XXX)XXXXXXX

The pre-filled message will automatically appear in the text field of a chat. Use https://wa.me/whatsappphonenumber?text=urlencodedtext where whatsappphonenumber is a full phone number in international format and urlencodedtext is the URL-encoded pre-filled message.

Example: https://wa.me/1XXXXXXXXXX?text=I'm%20interested%20in%20your%20car%20for%20sale

To create a link with just a pre-filled message, use https://wa.me/?text=urlencodedtext

Example: https://wa.me/?text=I'm%20inquiring%20about%20the%20apartment%20listing`

After clicking on the link, you’ll be shown a list of contacts you can send your message to.

Retrieve data from website in android app

Use this

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.someplace.com");
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);

This can be used to grab the whole webpage as a string of html, i.e., "<html>...</html>"

Note You need to declare the following 'uses-permission' in the android manifest xml file... answer by @Squonk here

And also check this answer

Check if a div does NOT exist with javascript

Try getting the element with the ID and check if the return value is null:

document.getElementById('some_nonexistent_id') === null

If you're using jQuery, you can do:

$('#some_nonexistent_id').length === 0

What are the differences between struct and class in C++?

While implied by other answers, it's not explicitly mentioned - that structs are C compatible, depending on usage; classes are not.

This means if you're writing a header that you want to be C compatible then you've no option other than struct (which in the C world can't have functions; but can have function pointers).

How to use Apple's new San Francisco font on a webpage

-apple-system allows you to pick San Francisco in Safari. BlinkMacSystemFont is the corresponding alternative for Chrome.

font-family: -apple-system, BlinkMacSystemFont, sans-serif;

Roboto or Helvetica Neue could be inserted as fallbacks even before sans-serif.

https://www.smashingmagazine.com/2015/11/using-system-ui-fonts-practical-guide/#details-of-approach-a (how or previously http://furbo.org/2015/07/09/i-left-my-system-fonts-in-san-francisco/ do a great job explaining the details.

MySQL count occurrences greater than 2

The HAVING option can be used for this purpose and query should be

SELECT word, COUNT(*) FROM words 
GROUP BY word
HAVING COUNT(*) > 1;

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

.col-xs-$   Extra Small     Phones Less than 768px 
.col-sm-$   Small Devices   Tablets 768px and Up 
.col-md-$   Medium Devices  Desktops 992px and Up 
.col-lg-$   Large Devices   Large Desktops 1200px and Up 

Keyboard shortcuts are not active in Visual Studio with Resharper installed

This one worked for me

RESHARPER > OPTIONS > select visual studio (Under Keyboard Shortcuts)

VS + Resharper

Add object to ArrayList at specified index

How about this little while loop as a solution?

private ArrayList<Object> list = new ArrayList<Object>();

private void addObject(int i, Object object) {
    while(list.size() < i) {
        list.add(list.size(), null);
    }
    list.add(i, object);
}
....

addObject(1, object1)
addObject(3, object3)
addObject(2, object2)

How to get 'System.Web.Http, Version=5.2.3.0?

Uninstalling and re-installing the NuGet package worked for me.

  1. Remove any old reference from the project.

Execute this in the Package Manager Console:

  1. UnInstall-Package Microsoft.AspNet.WebApi.Core -version 5.2.3
  2. Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

How to check syslog in Bash on Linux?

If you like Vim, it has built-in syntax highlighting for the syslog file, e.g. it will highlight error messages in red.

vi +'syntax on' /var/log/syslog

How to use continue in jQuery each() loop?

$('.submit').filter(':checked').each(function() {
    //This is same as 'continue'
    if(something){
        return true;
    }
    //This is same as 'break'
    if(something){
        return false;
    }
});

How to change max_allowed_packet size

For anyone running MySQL on Amazon RDS service, this change is done via parameter groups. You need to create a new PG or use an existing one (other than the default, which is read-only).

You should search for the max_allowed_packet parameter, change its value, and then hit save.

Back in your MySQL instance, if you created a new PG, you should attach the PG to your instance (you may need a reboot). If you changed a PG that was already attached to your instance, changes will be applied without reboot, to all your instances that have that PG attached.

PostgreSQL create table if not exists

This solution is somewhat similar to the answer by Erwin Brandstetter, but uses only the sql language.

Not all PostgreSQL installations has the plpqsql language by default, this means you may have to call CREATE LANGUAGE plpgsql before creating the function, and afterwards have to remove the language again, to leave the database in the same state as it was before (but only if the database did not have the plpgsql language to begin with). See how the complexity grows?

Adding the plpgsql may not be issue if you are running your script locally, however, if the script is used to set up schema at a customer it may not be desirable to leave changes like this in the customers database.

This solution is inspired by a post by Andreas Scherbaum.

-- Function which creates table
CREATE OR REPLACE FUNCTION create_table () RETURNS TEXT AS $$
    CREATE TABLE table_name (
       i int
    );
    SELECT 'extended_recycle_bin created'::TEXT;
    $$
LANGUAGE 'sql';

-- Test if table exists, and if not create it
SELECT CASE WHEN (SELECT true::BOOLEAN
    FROM   pg_catalog.pg_tables 
    WHERE  schemaname = 'public'
    AND    tablename  = 'table_name'
  ) THEN (SELECT 'success'::TEXT)
  ELSE (SELECT create_table())
END;

-- Drop function
DROP FUNCTION create_table();

How to filter an array from all elements of another array

All the above solutions "work", but are less than optimal for performance and are all approach the problem in the same way which is linearly searching all entries at each point using Array.prototype.indexOf or Array.prototype.includes. A far faster solution (far faster even than a binary search for most cases) would be to sort the arrays and skip ahead as you go along as seen below. However, one downside is that this requires all entries in the array to be numbers or strings. Also however, binary search may in some rare cases be faster than the progressive linear search. These cases arise from the fact that my progressive linear search has a complexity of O(2n1+n2) (only O(n1+n2) in the faster C/C++ version) (where n1 is the searched array and n2 is the filter array), whereas the binary search has a complexity of O(n1ceil(log2n2)) (ceil = round up -- to the ceiling), and, lastly, the indexOf search has a highly variable complexity between O(n1) and O(n1n2), averaging out to O(n1ceil(n2÷2)). Thus, indexOf will only be the fastest, on average, in the cases of (n1,n2) equaling {1,2}, {1,3}, or {x,1|x?N}. However, this is still not a perfect representation of modern hardware. IndexOf is natively optimized to the fullest extent imaginable in most modern browsers, making it very subject to the laws of branch prediction. Thus, if we make the same assumption on indexOf as we do with progressive linear and binary search -- that the array is presorted -- then, according to the stats listed in the link, we can expect roughly a 6x speed up for IndexOf, shifting its complexity to between O(n1÷6) and O(n1n2), averaging out to O(n1ceil(n27÷12)). Finally, take note that the below solution will never work with objects because objects in JavaScript cannot be compared by pointers in JavaScript.

function sortAnyArray(a,b) { return a>b ? 1 : (a===b ? 0 : -1); }
function sortIntArray(a,b) { return (a|0) - (b|0) |0; }
function fastFilter(array, handle) {
    var out=[], value=0;
    for (var i=0,  len=array.length|0; i < len; i=i+1|0)
        if (handle(value = array[i])) 
            out.push( value );
    return out;
}

const Math_clz32 = Math.clz32 || (function(log, LN2){
  return function(x) {
    return 31 - log(x >>> 0) / LN2 | 0; // the "| 0" acts like math.floor
  };
})(Math.log, Math.LN2);

/* USAGE:
  filterArrayByAnotherArray(
      [1,3,5],
      [2,3,4]
  ) yields [1, 5], and it can work with strings too
*/
function filterArrayByAnotherArray(searchArray, filterArray) {
    if (
        // NOTE: This does not check the whole array. But, if you know
        //        that there are only strings or numbers (not a mix of
        //        both) in the array, then this is a safe assumption.
        // Always use `==` with `typeof` because browsers can optimize
        //  the `==` into `===` (ONLY IN THIS CIRCUMSTANCE)
        typeof searchArray[0] == "number" &&
        typeof filterArray[0] == "number" &&
        (searchArray[0]|0) === searchArray[0] &&
        (filterArray[0]|0) === filterArray[0]
    ) {filterArray
        // if all entries in both arrays are integers
        searchArray.sort(sortIntArray);
        filterArray.sort(sortIntArray);
    } else {
        searchArray.sort(sortAnyArray);
        filterArray.sort(sortAnyArray);
    }
    var searchArrayLen = searchArray.length, filterArrayLen = filterArray.length;
    var progressiveLinearComplexity = ((searchArrayLen<<1) + filterArrayLen)>>>0
    var binarySearchComplexity= (searchArrayLen * (32-Math_clz32(filterArrayLen-1)))>>>0;
    // After computing the complexity, we can predict which algorithm will be the fastest
    var i = 0;
    if (progressiveLinearComplexity < binarySearchComplexity) {
        // Progressive Linear Search
        return fastFilter(searchArray, function(currentValue){
            while (filterArray[i] < currentValue) i=i+1|0;
            // +undefined = NaN, which is always false for <, avoiding an infinite loop
            return filterArray[i] !== currentValue;
        });
    } else {
        // Binary Search
        return fastFilter(
            searchArray,
            fastestBinarySearch(filterArray)
        );
    }
}

// see https://stackoverflow.com/a/44981570/5601591 for implementation
//  details about this binary search algorithm

function fastestBinarySearch(array){
  var initLen = (array.length|0) - 1 |0;
  
  const compGoto = Math_clz32(initLen) & 31;
  return function(sValue) {
    var len = initLen |0;
    switch (compGoto) {
      case 0:
        if (len & 0x80000000) {
          const nCB = len & 0x80000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 1:
        if (len & 0x40000000) {
          const nCB = len & 0xc0000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 2:
        if (len & 0x20000000) {
          const nCB = len & 0xe0000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 3:
        if (len & 0x10000000) {
          const nCB = len & 0xf0000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 4:
        if (len & 0x8000000) {
          const nCB = len & 0xf8000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 5:
        if (len & 0x4000000) {
          const nCB = len & 0xfc000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 6:
        if (len & 0x2000000) {
          const nCB = len & 0xfe000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 7:
        if (len & 0x1000000) {
          const nCB = len & 0xff000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 8:
        if (len & 0x800000) {
          const nCB = len & 0xff800000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 9:
        if (len & 0x400000) {
          const nCB = len & 0xffc00000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 10:
        if (len & 0x200000) {
          const nCB = len & 0xffe00000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 11:
        if (len & 0x100000) {
          const nCB = len & 0xfff00000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 12:
        if (len & 0x80000) {
          const nCB = len & 0xfff80000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 13:
        if (len & 0x40000) {
          const nCB = len & 0xfffc0000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 14:
        if (len & 0x20000) {
          const nCB = len & 0xfffe0000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 15:
        if (len & 0x10000) {
          const nCB = len & 0xffff0000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 16:
        if (len & 0x8000) {
          const nCB = len & 0xffff8000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 17:
        if (len & 0x4000) {
          const nCB = len & 0xffffc000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 18:
        if (len & 0x2000) {
          const nCB = len & 0xffffe000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 19:
        if (len & 0x1000) {
          const nCB = len & 0xfffff000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 20:
        if (len & 0x800) {
          const nCB = len & 0xfffff800;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 21:
        if (len & 0x400) {
          const nCB = len & 0xfffffc00;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 22:
        if (len & 0x200) {
          const nCB = len & 0xfffffe00;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 23:
        if (len & 0x100) {
          const nCB = len & 0xffffff00;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 24:
        if (len & 0x80) {
          const nCB = len & 0xffffff80;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 25:
        if (len & 0x40) {
          const nCB = len & 0xffffffc0;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 26:
        if (len & 0x20) {
          const nCB = len & 0xffffffe0;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 27:
        if (len & 0x10) {
          const nCB = len & 0xfffffff0;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 28:
        if (len & 0x8) {
          const nCB = len & 0xfffffff8;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 29:
        if (len & 0x4) {
          const nCB = len & 0xfffffffc;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 30:
        if (len & 0x2) {
          const nCB = len & 0xfffffffe;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 31:
        if (len & 0x1) {
          const nCB = len & 0xffffffff;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
    }
    // MODIFICATION: Instead of returning the index, this binary search
    //                instead returns whether something was found or not.
    if (array[len|0] !== sValue) {
       return true; // preserve the value at this index
    } else {
       return false; // eliminate the value at this index
    }
  };
}

Please see my other post here for more details on the binary search algorithm used

If you are squeamish about file size (which I respect), then you can sacrifice a little performance in order to greatly reduce the file size and increase maintainability.

function sortAnyArray(a,b) { return a>b ? 1 : (a===b ? 0 : -1); }
function sortIntArray(a,b) { return (a|0) - (b|0) |0; }
function fastFilter(array, handle) {
    var out=[], value=0;
    for (var i=0,  len=array.length|0; i < len; i=i+1|0)
        if (handle(value = array[i])) 
            out.push( value );
    return out;
}

/* USAGE:
  filterArrayByAnotherArray(
      [1,3,5],
      [2,3,4]
  ) yields [1, 5], and it can work with strings too
*/
function filterArrayByAnotherArray(searchArray, filterArray) {
    if (
        // NOTE: This does not check the whole array. But, if you know
        //        that there are only strings or numbers (not a mix of
        //        both) in the array, then this is a safe assumption.
        typeof searchArray[0] == "number" &&
        typeof filterArray[0] == "number" &&
        (searchArray[0]|0) === searchArray[0] &&
        (filterArray[0]|0) === filterArray[0]
    ) {
        // if all entries in both arrays are integers
        searchArray.sort(sortIntArray);
        filterArray.sort(sortIntArray);
    } else {
        searchArray.sort(sortAnyArray);
        filterArray.sort(sortAnyArray);
    }
    // Progressive Linear Search
    var i = 0;
    return fastFilter(searchArray, function(currentValue){
        while (filterArray[i] < currentValue) i=i+1|0;
        // +undefined = NaN, which is always false for <, avoiding an infinite loop
        return filterArray[i] !== currentValue;
    });
}

To prove the difference in speed, let us examine some JSPerfs. For filtering an array of 16 elements, binary search is roughly 17% faster than indexOf while filterArrayByAnotherArray is roughly 93% faster than indexOf. For filtering an array of 256 elements, binary search is roughly 291% faster than indexOf while filterArrayByAnotherArray is roughly 353% faster than indexOf. For filtering an array of 4096 elements, binary search is roughly 2655% faster than indexOf while filterArrayByAnotherArray is roughly 4627% faster than indexOf.

Reverse-filtering (like an AND gate)

The previous section provided code to take array A and array B, and remove all elements from A that exist in B:

filterArrayByAnotherArray(
    [1,3,5],
    [2,3,4]
);
// yields [1, 5]

This next section will provide code for reverse-filtering, where we remove all elements from A that DO NOT exist in B. This process is functionally equivalent to only retaining the elements common to both A and B, like an AND gate:

reverseFilterArrayByAnotherArray(
    [1,3,5],
    [2,3,4]
);
// yields [3]

Here is the code for reverse filtering:

function sortAnyArray(a,b) { return a>b ? 1 : (a===b ? 0 : -1); }
function sortIntArray(a,b) { return (a|0) - (b|0) |0; }
function fastFilter(array, handle) {
    var out=[], value=0;
    for (var i=0,  len=array.length|0; i < len; i=i+1|0)
        if (handle(value = array[i])) 
            out.push( value );
    return out;
}

const Math_clz32 = Math.clz32 || (function(log, LN2){
  return function(x) {
    return 31 - log(x >>> 0) / LN2 | 0; // the "| 0" acts like math.floor
  };
})(Math.log, Math.LN2);

/* USAGE:
  reverseFilterArrayByAnotherArray(
      [1,3,5],
      [2,3,4]
  ) yields [3], and it can work with strings too
*/
function reverseFilterArrayByAnotherArray(searchArray, filterArray) {
    if (
        // NOTE: This does not check the whole array. But, if you know
        //        that there are only strings or numbers (not a mix of
        //        both) in the array, then this is a safe assumption.
        // Always use `==` with `typeof` because browsers can optimize
        //  the `==` into `===` (ONLY IN THIS CIRCUMSTANCE)
        typeof searchArray[0] == "number" &&
        typeof filterArray[0] == "number" &&
        (searchArray[0]|0) === searchArray[0] &&
        (filterArray[0]|0) === filterArray[0]
    ) {
        // if all entries in both arrays are integers
        searchArray.sort(sortIntArray);
        filterArray.sort(sortIntArray);
    } else {
        searchArray.sort(sortAnyArray);
        filterArray.sort(sortAnyArray);
    }
    var searchArrayLen = searchArray.length, filterArrayLen = filterArray.length;
    var progressiveLinearComplexity = ((searchArrayLen<<1) + filterArrayLen)>>>0
    var binarySearchComplexity= (searchArrayLen * (32-Math_clz32(filterArrayLen-1)))>>>0;
    // After computing the complexity, we can predict which algorithm will be the fastest
    var i = 0;
    if (progressiveLinearComplexity < binarySearchComplexity) {
        // Progressive Linear Search
        return fastFilter(searchArray, function(currentValue){
            while (filterArray[i] < currentValue) i=i+1|0;
            // +undefined = NaN, which is always false for <, avoiding an infinite loop
            // For reverse filterning, I changed !== to ===
            return filterArray[i] === currentValue;
        });
    } else {
        // Binary Search
        return fastFilter(
            searchArray,
            inverseFastestBinarySearch(filterArray)
        );
    }
}

// see https://stackoverflow.com/a/44981570/5601591 for implementation
//  details about this binary search algorithim

function inverseFastestBinarySearch(array){
  var initLen = (array.length|0) - 1 |0;
  
  const compGoto = Math_clz32(initLen) & 31;
  return function(sValue) {
    var len = initLen |0;
    switch (compGoto) {
      case 0:
        if (len & 0x80000000) {
          const nCB = len & 0x80000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 1:
        if (len & 0x40000000) {
          const nCB = len & 0xc0000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 2:
        if (len & 0x20000000) {
          const nCB = len & 0xe0000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 3:
        if (len & 0x10000000) {
          const nCB = len & 0xf0000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 4:
        if (len & 0x8000000) {
          const nCB = len & 0xf8000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 5:
        if (len & 0x4000000) {
          const nCB = len & 0xfc000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 6:
        if (len & 0x2000000) {
          const nCB = len & 0xfe000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 7:
        if (len & 0x1000000) {
          const nCB = len & 0xff000000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 8:
        if (len & 0x800000) {
          const nCB = len & 0xff800000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 9:
        if (len & 0x400000) {
          const nCB = len & 0xffc00000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 10:
        if (len & 0x200000) {
          const nCB = len & 0xffe00000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 11:
        if (len & 0x100000) {
          const nCB = len & 0xfff00000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 12:
        if (len & 0x80000) {
          const nCB = len & 0xfff80000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 13:
        if (len & 0x40000) {
          const nCB = len & 0xfffc0000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 14:
        if (len & 0x20000) {
          const nCB = len & 0xfffe0000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 15:
        if (len & 0x10000) {
          const nCB = len & 0xffff0000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 16:
        if (len & 0x8000) {
          const nCB = len & 0xffff8000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 17:
        if (len & 0x4000) {
          const nCB = len & 0xffffc000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 18:
        if (len & 0x2000) {
          const nCB = len & 0xffffe000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 19:
        if (len & 0x1000) {
          const nCB = len & 0xfffff000;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 20:
        if (len & 0x800) {
          const nCB = len & 0xfffff800;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 21:
        if (len & 0x400) {
          const nCB = len & 0xfffffc00;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 22:
        if (len & 0x200) {
          const nCB = len & 0xfffffe00;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 23:
        if (len & 0x100) {
          const nCB = len & 0xffffff00;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 24:
        if (len & 0x80) {
          const nCB = len & 0xffffff80;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 25:
        if (len & 0x40) {
          const nCB = len & 0xffffffc0;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 26:
        if (len & 0x20) {
          const nCB = len & 0xffffffe0;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 27:
        if (len & 0x10) {
          const nCB = len & 0xfffffff0;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 28:
        if (len & 0x8) {
          const nCB = len & 0xfffffff8;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 29:
        if (len & 0x4) {
          const nCB = len & 0xfffffffc;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 30:
        if (len & 0x2) {
          const nCB = len & 0xfffffffe;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
      case 31:
        if (len & 0x1) {
          const nCB = len & 0xffffffff;
          len ^= (len ^ (nCB-1)) & ((array[nCB] <= sValue |0) - 1 >>>0);
        }
    }
    // MODIFICATION: Instead of returning the index, this binary search
    //                instead returns whether something was found or not.
    // For reverse filterning, I swapped true with false and vice-versa
    if (array[len|0] !== sValue) {
       return false; // preserve the value at this index
    } else {
       return true; // eliminate the value at this index
    }
  };
}

For the slower smaller version of the reverse filtering code, see below.

function sortAnyArray(a,b) { return a>b ? 1 : (a===b ? 0 : -1); }
function sortIntArray(a,b) { return (a|0) - (b|0) |0; }
function fastFilter(array, handle) {
    var out=[], value=0;
    for (var i=0,  len=array.length|0; i < len; i=i+1|0)
        if (handle(value = array[i])) 
            out.push( value );
    return out;
}

/* USAGE:
  reverseFilterArrayByAnotherArray(
      [1,3,5],
      [2,3,4]
  ) yields [3], and it can work with strings too
*/
function reverseFilterArrayByAnotherArray(searchArray, filterArray) {
    if (
        // NOTE: This does not check the whole array. But, if you know
        //        that there are only strings or numbers (not a mix of
        //        both) in the array, then this is a safe assumption.
        typeof searchArray[0] == "number" &&
        typeof filterArray[0] == "number" &&
        (searchArray[0]|0) === searchArray[0] &&
        (filterArray[0]|0) === filterArray[0]
    ) {
        // if all entries in both arrays are integers
        searchArray.sort(sortIntArray);
        filterArray.sort(sortIntArray);
    } else {
        searchArray.sort(sortAnyArray);
        filterArray.sort(sortAnyArray);
    }
    // Progressive Linear Search
    var i = 0;
    return fastFilter(searchArray, function(currentValue){
        while (filterArray[i] < currentValue) i=i+1|0;
        // +undefined = NaN, which is always false for <, avoiding an infinite loop
        // For reverse filter, I changed !== to ===
        return filterArray[i] === currentValue;
    });
}

Android: Color To Int conversion

R.color.black or some color are obviously integers. It needs a RGB value. You can give your own like #FF123454 which represents various primary colors

What is the difference between #import and #include in Objective-C?

#include works just like the C #include.

#import keeps track of which headers have already been included and is ignored if a header is imported more than once in a compilation unit. This makes it unnecessary to use header guards.

The bottom line is just use #import in Objective-C and don't worry if your headers wind up importing something more than once.

jQuery UI Sortable Position

You can use the ui object provided to the events, specifically you want the stop event, the ui.item property and .index(), like this:

$("#sortable").sortable({
    stop: function(event, ui) {
        alert("New position: " + ui.item.index());
    }
});

You can see a working demo here, remember the .index() value is zero-based, so you may want to +1 for display purposes.

Difference between Key, Primary Key, Unique Key and Index in MySQL

Primary key does not allow NULL values, but unique key allows NULL values.

We can declare only one primary key in a table, but a table can have multiple unique keys (column assign).

Disable all table constraints in Oracle

It is better to avoid writing out temporary spool files. Use a PL/SQL block. You can run this from SQL*Plus or put this thing into a package or procedure. The join to USER_TABLES is there to avoid view constraints.

It's unlikely that you really want to disable all constraints (including NOT NULL, primary keys, etc). You should think about putting constraint_type in the WHERE clause.

BEGIN
  FOR c IN
  (SELECT c.owner, c.table_name, c.constraint_name
   FROM user_constraints c, user_tables t
   WHERE c.table_name = t.table_name
   AND c.status = 'ENABLED'
   AND NOT (t.iot_type IS NOT NULL AND c.constraint_type = 'P')
   ORDER BY c.constraint_type DESC)
  LOOP
    dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" disable constraint ' || c.constraint_name);
  END LOOP;
END;
/

Enabling the constraints again is a bit tricker - you need to enable primary key constraints before you can reference them in a foreign key constraint. This can be done using an ORDER BY on constraint_type. 'P' = primary key, 'R' = foreign key.

BEGIN
  FOR c IN
  (SELECT c.owner, c.table_name, c.constraint_name
   FROM user_constraints c, user_tables t
   WHERE c.table_name = t.table_name
   AND c.status = 'DISABLED'
   ORDER BY c.constraint_type)
  LOOP
    dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" enable constraint ' || c.constraint_name);
  END LOOP;
END;
/

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

An addition to the answer by bobince ...

With Ajax you can have your 'Logout' link/button wired to a Javascript function. Have this function send the XMLHttpRequest with a bad username and password. This should get back a 401. Then set document.location back to the pre-login page. This way, the user will never see the extra login dialog during logout, nor have to remember to put in bad credentials.

Android Intent Cannot resolve constructor

Using .getActivity() solves this issue:

For eg.

Intent i= new Intent(MainActivity.this.getActivity(), Next.class);
startActivity(i);

Hope this helps.

Cheers.

Session TimeOut in web.xml

Send AJAX Http Requests to the server periodically (say once for every 60 seconds) through javascript to maintain session with the server until the file upload gets completed.

LINQ to Entities does not recognize the method

If anyone is looking for a VB.Net answer (as I was initially), here it is:

Public Function IsSatisfied() As Expression(Of Func(Of Charity, String, String, Boolean))

Return Function(charity, name, referenceNumber) (String.IsNullOrWhiteSpace(name) Or
                                                         charity.registeredName.ToLower().Contains(name.ToLower()) Or
                                                         charity.alias.ToLower().Contains(name.ToLower()) Or
                                                         charity.charityId.ToLower().Contains(name.ToLower())) And
                                                    (String.IsNullOrEmpty(referenceNumber) Or
                                                     charity.charityReference.ToLower().Contains(referenceNumber.ToLower()))
End Function

Java: is there a map function?

There is a wonderful library called Functional Java which handles many of the things you'd want Java to have but it doesn't. Then again, there's also this wonderful language Scala which does everything Java should have done but doesn't while still being compatible with anything written for the JVM.

How to pretty-print a numpy.array without scientific notation and with given precision?

I find that the usual float format {:9.5f} works properly -- suppressing small-value e-notations -- when displaying a list or an array using a loop. But that format sometimes fails to suppress its e-notation when a formatter has several items in a single print statement. For example:

import numpy as np
np.set_printoptions(suppress=True)
a3 = 4E-3
a4 = 4E-4
a5 = 4E-5
a6 = 4E-6
a7 = 4E-7
a8 = 4E-8
#--first, display separate numbers-----------
print('Case 3:  a3, a4, a5:             {:9.5f}{:9.5f}{:9.5f}'.format(a3,a4,a5))
print('Case 4:  a3, a4, a5, a6:         {:9.5f}{:9.5f}{:9.5f}{:9.5}'.format(a3,a4,a5,a6))
print('Case 5:  a3, a4, a5, a6, a7:     {:9.5f}{:9.5f}{:9.5f}{:9.5}{:9.5f}'.format(a3,a4,a5,a6,a7))
print('Case 6:  a3, a4, a5, a6, a7, a8: {:9.5f}{:9.5f}{:9.5f}{:9.5f}{:9.5}{:9.5f}'.format(a3,a4,a5,a6,a7,a8))
#---second, display a list using a loop----------
myList = [a3,a4,a5,a6,a7,a8]
print('List 6:  a3, a4, a5, a6, a7, a8: ', end='')
for x in myList: 
    print('{:9.5f}'.format(x), end='')
print()
#---third, display a numpy array using a loop------------
myArray = np.array(myList)
print('Array 6: a3, a4, a5, a6, a7, a8: ', end='')
for x in myArray:
    print('{:9.5f}'.format(x), end='')
print()

My results show the bug in cases 4, 5, and 6:

Case 3:  a3, a4, a5:               0.00400  0.00040  0.00004
Case 4:  a3, a4, a5, a6:           0.00400  0.00040  0.00004    4e-06
Case 5:  a3, a4, a5, a6, a7:       0.00400  0.00040  0.00004    4e-06  0.00000
Case 6:  a3, a4, a5, a6, a7, a8:   0.00400  0.00040  0.00004  0.00000    4e-07  0.00000
List 6:  a3, a4, a5, a6, a7, a8:   0.00400  0.00040  0.00004  0.00000  0.00000  0.00000
Array 6: a3, a4, a5, a6, a7, a8:   0.00400  0.00040  0.00004  0.00000  0.00000  0.00000

I have no explanation for this, and therefore I always use a loop for floating output of multiple values.

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Your syntax is pretty screwy.

Change this:

input:not(disabled)not:[type="submit"]:focus{

to:

input:not(:disabled):not([type="submit"]):focus{

Seems that many people don't realize :enabled and :disabled are valid CSS selectors...

How to compare two dates in php

You can to converte for integer number and compare.

Eg.:

$date_1 = date('Ymd');
$date_2 = '31_12_2011';

$date_2 = (int) implode(array_reverse(explode("_", $date_2)));

echo ($date_1 < $date_2) ? '$date_2 is bigger then $date_1' : '$date_2 is smaller than $date_1';

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

if x is numeric, then add scale_x_continuous(); if x is character/factor, then add scale_x_discrete(). This might solve your problem.

Conversion of Char to Binary in C

unsigned char c;

for( int i = 7; i >= 0; i-- ) {
    printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}

printf("\n");

Explanation:

With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.

For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.

How to write a basic swap function in Java

  class Swap2Values{
    public static void main(String[] args){
       int a = 20, b = 10;

       //before swaping
       System.out.print("Before Swapping the values of a and b are: a = "+a+", b = "+b);

       //swapping
       a = a + b;
       b = a - b;
       a = a - b;

       //after swapping
      System.out.print("After Swapping the values of a and b are: a = "+a+", b = "+b);
    }
  }

Jackson - How to process (deserialize) nested JSON?

I'm quite late to the party, but one approach is to use a static inner class to unwrap values:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

class Scratch {
    private final String aString;
    private final String bString;
    private final String cString;
    private final static String jsonString;

    static {
        jsonString = "{\n" +
                "  \"wrap\" : {\n" +
                "    \"A\": \"foo\",\n" +
                "    \"B\": \"bar\",\n" +
                "    \"C\": \"baz\"\n" +
                "  }\n" +
                "}";
    }

    @JsonCreator
    Scratch(@JsonProperty("A") String aString,
            @JsonProperty("B") String bString,
            @JsonProperty("C") String cString) {
        this.aString = aString;
        this.bString = bString;
        this.cString = cString;
    }

    @Override
    public String toString() {
        return "Scratch{" +
                "aString='" + aString + '\'' +
                ", bString='" + bString + '\'' +
                ", cString='" + cString + '\'' +
                '}';
    }

    public static class JsonDeserializer {
        private final Scratch scratch;

        @JsonCreator
        public JsonDeserializer(@JsonProperty("wrap") Scratch scratch) {
            this.scratch = scratch;
        }

        public Scratch getScratch() {
            return scratch;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Scratch scratch = objectMapper.readValue(jsonString, Scratch.JsonDeserializer.class).getScratch();
        System.out.println(scratch.toString());
    }
}

However, it's probably easier to use objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true); in conjunction with @JsonRootName("aName"), as pointed out by pb2q

JavaScript DOM: Find Element Index In Container

2017 update

The original answer below assumes that the OP wants to include non-empty text node and other node types as well as elements. It doesn't seem clear to me now from the question whether this is a valid assumption.

Assuming instead you just want the element index, previousElementSibling is now well-supported (which was not the case in 2012) and is the obvious choice now. The following (which is the same as some other answers here) will work in everything major except IE <= 8.

function getElementIndex(node) {
    var index = 0;
    while ( (node = node.previousElementSibling) ) {
        index++;
    }
    return index;
}

Original answer

Just use previousSibling until you hit null. I'm assuming you want to ignore white space-only text nodes; if you want to filter other nodes then adjust accordingly.

function getNodeIndex(node) {
    var index = 0;
    while ( (node = node.previousSibling) ) {
        if (node.nodeType != 3 || !/^\s*$/.test(node.data)) {
            index++;
        }
    }
    return index;
}

Counting number of occurrences in column?

Try:

=ArrayFormula(QUERY(A:A&{"",""};"select Col1, count(Col2) where Col1 != '' group by Col1 label count(Col2) 'Count'";1))


22/07/2014 Some time in the last month, Sheets has started supporting more flexible concatenation of arrays, using an embedded array. So the solution may be shortened slightly to:

=QUERY({A:A,A:A},"select Col1, count(Col2) where Col1 != '' group by Col1 label count(Col2) 'Count'",1)

How to go back (ctrl+z) in vi/vim

You can use the u button to undo the last modification. (And Ctrl+R to redo it).

Read more about it at: http://vim.wikia.com/wiki/Undo_and_Redo

How to call a .NET Webservice from Android using KSOAP2?

If more than one result is expected, then the getResponse() method will return a Vector containing the various responses.

In which case the offending code becomes:

Object result = envelope.getResponse();

// treat result as a vector
String resultText = null;
if (result instanceof Vector)
{
    SoapPrimitive element0 = (SoapPrimitive)((Vector) result).elementAt(0);
    resultText = element0.toString();
}

tv.setText(resultText);

Answer based on the ksoap2-android (mosabua fork)

Proper usage of Optional.ifPresent()

You can use method reference like this:

user.ifPresent(ClassNameWhereMethodIs::doSomethingWithUser);

Method ifPresent() get Consumer object as a paremeter and (from JavaDoc): "If a value is present, invoke the specified consumer with the value." Value it is your variable user.

Or if this method doSomethingWithUser is in the User class and it is not static, you can use method reference like this:

user.ifPresent(this::doSomethingWithUser);

What do "branch", "tag" and "trunk" mean in Subversion repositories?

Trunk : After the completion of every sprint in agile we come out with a partially shippable product. These releases are kept in trunk.

Branches : All parallel developments codes for each ongoing sprint are kept in branches.

Tags : Every time we release a partially shippable product kind of beta version, we make a tag for it. This gives us the code that was available at that point of time, allowing us to go back at that state if required at some point during development.

curl -GET and -X GET

-X [your method]
X lets you override the default 'Get'

** corrected lowercase x to uppercase X

Open Cygwin at a specific folder

Find file Cygwin.bat and make content like this:

@echo off
set newpath=%cd:\=/%
pushd "%~dp0"
chdir bin
bash --login -i -c "cd \"%newpath%\"; exec bash"

Add path to cygwin.bat to environment PATH.

Now in any folder you can type to address bar:

cygwin

Also you can type it when you in cmd.exe

How to do integer division in javascript (Getting division answer in int not float)?

var answer = Math.floor(x)

I sincerely hope this will help future searchers when googling for this common question.

Running Bash commands in Python

It is possible you use the bash program, with the parameter -c for execute the commands:

bashCommand = "cwm --rdf test.rdf --ntriples > test.nt"
output = subprocess.check_output(['bash','-c', bashCommand])

How to use sha256 in php5.3.0

A way better solution is to just use the excelent compatibility script from Anthony Ferrara:

https://github.com/ircmaxell/password_compat

Please, and also, when checking the password, always add a way (preferibly async, so it doesn't impact the check process for timming attacks) to update the hash if needed.

LINUX: Link all files from one to another directory

ln -s /mnt/usr/lib/* /usr/lib/

I guess, this belongs to superuser, though.

Clear Application's Data Programmatically

There's a new API introduced in API 19 (KitKat): ActivityManager.clearApplicationUserData().

I highly recommend using it in new applications:

import android.os.Build.*;
if (VERSION_CODES.KITKAT <= VERSION.SDK_INT) {
    ((ActivityManager)context.getSystemService(ACTIVITY_SERVICE))
            .clearApplicationUserData(); // note: it has a return value!
} else {
    // use old hacky way, which can be removed
    // once minSdkVersion goes above 19 in a few years.
}

If you don't want the hacky way you can also hide the button on the UI, so that functionality is just not available on old phones.

Knowledge of this method is mandatory for anyone using android:manageSpaceActivity.


Whenever I use this, I do so from a manageSpaceActivity which has android:process=":manager". There, I manually kill any other processes of my app. This allows me to let a UI stay running and let the user decide where to go next.

private static void killProcessesAround(Activity activity) throws NameNotFoundException {
    ActivityManager am = (ActivityManager)activity.getSystemService(Context.ACTIVITY_SERVICE);
    String myProcessPrefix = activity.getApplicationInfo().processName;
    String myProcessName = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0).processName;
    for (ActivityManager.RunningAppProcessInfo proc : am.getRunningAppProcesses()) {
        if (proc.processName.startsWith(myProcessPrefix) && !proc.processName.equals(myProcessName)) {
            android.os.Process.killProcess(proc.pid);
        }
    }
}

Convert java.util.Date to java.time.LocalDate

I solved this question with solution below

  import org.joda.time.LocalDate;
  Date myDate = new Date();
  LocalDate localDate = LocalDate.fromDateFields(myDate);
  System.out.println("My date using Date" Nov 18 11:23:33 BRST 2016);
  System.out.println("My date using joda.time LocalTime" 2016-11-18);

In this case localDate print your date in this format "yyyy-MM-dd"

How to copy Docker images from one host to another without using a repository

Transferring a Docker image via SSH, bzipping the content on the fly:

docker save <image> | bzip2 | \
     ssh user@host 'bunzip2 | docker load'

It's also a good idea to put pv in the middle of the pipe to see how the transfer is going:

docker save <image> | bzip2 | pv | \
     ssh user@host 'bunzip2 | docker load'

(More info about pv: home page, man page).

How can I get a user's media from Instagram without authenticating as a user?

I really needed this function but for Wordpress. I fit and it worked perfectly

<script>
    jQuery(function($){
        var name = "caririceara.comcariri";
        $.get("https://images"+~~(Math.random()*33)+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=https://www.instagram.com/" + name + "/", function(html) {
            if (html) {
                var regex = /_sharedData = ({.*);<\/script>/m,
                  json = JSON.parse(regex.exec(html)[1]),
                  edges = json.entry_data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media.edges;
              $.each(edges, function(n, edge) {
                   if (n <= 7){
                     var node = edge.node;
                    $('.img_ins').append('<a href="https://instagr.am/p/'+node.shortcode+'" target="_blank"><img src="'+node.thumbnail_src+'" width="150"></a>');
                   }
              });
            }
        });
    }); 
    </script>

How to add image in Flutter

their is no need to create asset directory and under it images directory and then you put image. Better is to just create Images directory inside your project where pubspec.yaml exist and put images inside it and access that images just like as shown in tutorial/documention

assets: - images/lake.jpg // inside pubspec.yaml

ImageView rounded corners

Now we no need to use any third party lib or custom imageView

Now We can use ShapeableImageView

SAMPLE CODE

First add below dependencies in your build.gradle file

implementation 'com.google.android.material:material:1.2.0-alpha05'

Make ImageView Circular from coding

Add ShapeableImageView in your layout

<com.google.android.material.imageview.ShapeableImageView
    android:id="@+id/myShapeableImageView"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_margin="20dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/nilesh" />

Kotlin code to make ImageView Circle

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.shape.CornerFamily
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


//        <dimen name="image_corner_radius">50dp</dimen>

        val radius = resources.getDimension(R.dimen.image_corner_radius)
        myShapeableImageView.shapeAppearanceModel = myShapeableImageView.shapeAppearanceModel
            .toBuilder()
            .setTopRightCorner(CornerFamily.ROUNDED, radius)
            .setTopLeftCorner(CornerFamily.ROUNDED, radius)
            .setBottomLeftCorner(CornerFamily.ROUNDED, radius)
            .setBottomRightCorner(CornerFamily.ROUNDED, radius)
            .build()

            // or  You can use setAllCorners() method

        myShapeableImageView.shapeAppearanceModel = myShapeableImageView.shapeAppearanceModel
            .toBuilder()
            .setAllCorners(CornerFamily.ROUNDED, radius)
            .build()


    }
}

OUTPUT

enter image description here

Make ImageView Circle from using a style

First, create a below style in your style.xml

<style name="circleImageViewStyle" >
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
</style>

Now use that style in your layout like this

<com.google.android.material.imageview.ShapeableImageView
    android:id="@+id/myShapeableImageView"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_margin="20dp"
    app:shapeAppearanceOverlay="@style/circleImageViewStyle"
    app:srcCompat="@drawable/nilesh" />

OUTPUT

enter image description here

Please find the complete exmaple here how to use ShapeableImageView

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

Why?

You asked why it happens, let's see:

The official language specificaion dictates a call to the internal [[GetValue]] method. Your .attr returns undefined and you're trying to access its length.

If Type(V) is not Reference, return V.

This is true, since undefined is not a reference (alongside null, number, string and boolean)

Let base be the result of calling GetBase(V).

This gets the undefined part of myVar.length .

If IsUnresolvableReference(V), throw a ReferenceError exception.

This is not true, since it is resolvable and it resolves to undefined.

If IsPropertyReference(V), then

This happens since it's a property reference with the . syntax.

Now it tries to convert undefined to a function which results in a TypeError.

What's the difference between display:inline-flex and display:flex?

The Difference between "flex" and "inline-flex"

Short answer:

One is inline and the other basically responds like a block element(but has some of it's own differences).

Longer answer:

Inline-Flex - The inline version of flex allows the element, and it's children, to have flex properties while still remaining in the regular flow of the document/webpage. Basically, you can place two inline flex containers in the same row, if the widths were small enough, without any excess styling to allow them to exist in the same row. This is pretty similar to "inline-block."

Flex - The container and it's children have flex properties but the container reserves the row, as it is taken out of the normal flow of the document. It responds like a block element, in terms of document flow. Two flexbox containers could not exist on the same row without excess styling.

The problem you may be having

Due to the elements you listed in your example, though I am guessing, I think you want to use flex to display the elements listed in an even row-by-row fashion but continue to see the elements side-by-side.

The reason you are likely having issues is because flex and inline-flex have the default "flex-direction" property set to "row." This will display the children side-by side. Changing this property to "column" will allow your elements to stack and reserve space(width) equal to the width of its parent.

Below are some examples to show how flex vs inline-flex works and also a quick demo of how inline vs block elements work...

display: inline-flex; flex-direction: row;

Fiddle

display: flex; flex-direction: row;

Fiddle

display: inline-flex; flex-direction: column;

Fiddle

display: flex; flex-direction: column;

Fiddle

display: inline;

Fiddle

display: block

Fiddle

Also, a great reference doc: A Complete Guide to Flexbox - css tricks

Singleton in Android

You are copying singleton's customVar into a singletonVar variable and changing that variable does not affect the original value in singleton.

// This does not update singleton variable
// It just assigns value of your local variable
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);

// This actually assigns value of variable in singleton
Singleton.customVar = singletonVar;

How to disable text selection using jQuery?

Here's a more comprehensive solution to the disconnect selection, and the cancellation of some of the hot keys (such as Ctrl+a and Ctrl+c. Test: Cmd+a and Cmd+c)

(function($){

  $.fn.ctrlCmd = function(key) {

    var allowDefault = true;

    if (!$.isArray(key)) {
       key = [key];
    }

    return this.keydown(function(e) {
        for (var i = 0, l = key.length; i < l; i++) {
            if(e.keyCode === key[i].toUpperCase().charCodeAt(0) && e.metaKey) {
                allowDefault = false;
            }
        };
        return allowDefault;
    });
};


$.fn.disableSelection = function() {

    this.ctrlCmd(['a', 'c']);

    return this.attr('unselectable', 'on')
               .css({'-moz-user-select':'-moz-none',
                     '-moz-user-select':'none',
                     '-o-user-select':'none',
                     '-khtml-user-select':'none',
                     '-webkit-user-select':'none',
                     '-ms-user-select':'none',
                     'user-select':'none'})
               .bind('selectstart', false);
};

})(jQuery);

and call example:

$(':not(input,select,textarea)').disableSelection();

jsfiddle.net/JBxnQ/

This could be also not enough for old versions of FireFox (I can't tell which). If all this does not work, add the following:

.on('mousedown', false)

How to hide elements without having them take space on the page?

display:none is the best thing to avoid takeup white space on the page

How do you declare string constants in C?

One advantage (albeit very slight) of defining string constants is that you can concatenate them at compile time:

#define HELLO "hello"
#define WORLD "world"

puts( HELLO WORLD );

Not sure that's really an advantage, but it is a technique that cannot be used with const char *'s.

AngularJS. How to call controller function from outside of controller component

I am an Ionic framework user and the one I found that would consistently provide the current controller's $scope is:

angular.element(document.querySelector('ion-view[nav-view="active"]')).scope()

I suspect this can be modified to fit most scenarios regardless of framework (or not) by finding the query that will target the specific DOM element(s) that are available only during a given controller instance.

MySQL - Operand should contain 1 column(s)

Another place this error can happen in is assigning a value that has a comma outside of a string. For example:

SET totalvalue = (IFNULL(i.subtotal,0) + IFNULL(i.tax,0),0)

MySql difference between two timestamps in days?

If you need the difference in days accounting up to the second:

SELECT TIMESTAMPDIFF(SECOND,'2010-09-21 21:40:36','2010-10-08 18:23:13')/86400 AS diff

It will return
diff
16.8629

How to set-up a favicon?

There is a very simple method to set a favicon, which had been around for a long time AFAIK. Place the favicon.ico file in the default location. i.e

http://www.yoursite.com/favicon.ico

This works in almost every browser without a <link> tag. However, this works only if it is an *.ico file. PNGs and other formats still have to be linked with a <link> tag

get path for my .exe

System.Reflection.Assembly.GetEntryAssembly().Location;

This view is not constrained

Solution

Just click this and it will be solved

Rename file with Git

Note that, from March 15th, 2013, you can move or rename a file directly from GitHub:

(you don't even need to clone that repo, git mv xx and git push back to GitHub!)

renaming

You can also move files to entirely new locations using just the filename field.
To navigate down into a folder, just type the name of the folder you want to move the file into followed by /.
The folder can be one that’s already part of your repository, or it can even be a brand-new folder that doesn’t exist yet!

moving

In Java, how can I determine if a char array contains a particular character?

You can iterate through the array or you can convert it to a String and use indexOf.

if (new String(charArray).indexOf('q') < 0) {
    break;
}

Creating a new String is a bit wasteful, but it's probably the tersest code. You can also write a method to imitate the effect without incurring the overhead.

How to access parameters in a Parameterized Build?

Hope the following piece of code works for you:

def item = hudson.model.Hudson.instance.getItem('MyJob')

def value = item.lastBuild.getEnvironment(null).get('foo')

How do I pass a datetime value as a URI parameter in asp.net mvc?

Since MVC 5 you can use the built in Attribute Routing package which supports a datetime type, which will accept anything that can be parsed to a DateTime.

e.g.

[GET("Orders/{orderDate:datetime}")]

More info here.

What is middleware exactly?

Lets say your company makes 4 different products, your client has another 3 different products from another 3 different companies.

Someday the client thought, why don't we integrate all our systems into one huge system. Ten minutes later their IT department said that will take 2 years.

You (the wise developer) said, why don't we just integrate all the different systems and make them work together in a homogeneous environment? The client manager staring at you... You continued, we will use a Middleware, we will study the Inputs/Outputs of all different systems, the resources they use and then choose an appropriate Middleware framework.

Still explaining to the non tech manager
With Middleware framework in the middle, the first system will produce X stuff, the system Y and Z would consume those outputs and so on.

Set height of chart in Chart.js

I created a container and set it the desired height of the view port (depending on the number of charts or chart specific sizes):

.graph-container {
width: 100%;
height: 30vh;
}

To be dynamic to screen sizes I set the container as follows:

*Small media devices specific styles*/
@media screen and (max-width: 800px) {
.graph-container {
        display: block;
        float: none;
        width: 100%;
        margin-top: 0px;
        margin-right:0px;
        margin-left:0px;
        height: auto;
    }
}

Of course very important (as have been referred to numerous times) set the following option properties of your chart:

options:{
    maintainAspectRatio: false,
    responsive: true,
}

Why use @Scripts.Render("~/bundles/jquery")

You can also use:

@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")

To specify the format of your output in a scenario where you need to use Charset, Type, etc.

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

In my specific case I seemed to have been missing the dependency

 <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>5.1.3.RELEASE</version>
 </dependency>

Find and extract a number from a string

Did the reverse of one of the answers to this question: How to remove numbers from string using Regex.Replace?

// Pull out only the numbers from the string using LINQ

var numbersFromString = new String(input.Where(x => x >= '0' && x <= '9').ToArray());

var numericVal = Int32.Parse(numbersFromString);

FIFO class in Java

Queues are First In First Out structures. You request is pretty vague, but I am guessing that you need only the basic functionality which usually comes out with Queue structures. You can take a look at how you can implement it here.

With regards to your missing package, it is most likely because you will need to either download or create the package yourself by following that tutorial.

What's the difference between Git Revert, Checkout and Reset?

If you broke the tree but didn't commit the code, you can use git reset, and if you just want to restore one file, you can use git checkout.

If you broke the tree and committed the code, you can use git revert HEAD.

http://book.git-scm.com/4_undoing_in_git_-_reset,_checkout_and_revert.html

Trim spaces from start and end of string

Note: As of 2015, all major browsers (including IE>=9) support String.prototype.trim(). This means that for most use cases simply doing str.trim() is the best way of achieving what the question asks.


Steven Levithan analyzed many different implementation of trim in Javascript in terms of performance.

His recommendation is:

function trim1 (str) {
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

for "general-purpose implementation which is fast cross-browser", and

function trim11 (str) {
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}

"if you want to handle long strings exceptionally fast in all browsers".

References

Performance differences between ArrayList and LinkedList

ArrayList is faster than LinkedList if I randomly access its elements. I think random access means "give me the nth element". Why ArrayList is faster?

ArrayList has direct references to every element in the list, so it can get the n-th element in constant time. LinkedList has to traverse the list from the beginning to get to the n-th element.

LinkedList is faster than ArrayList for deletion. I understand this one. ArrayList's slower since the internal backing-up array needs to be reallocated.

ArrayList is slower because it needs to copy part of the array in order to remove the slot that has become free. If the deletion is done using the ListIterator.remove() API, LinkedList just has to manipulate a couple of references; if the deletion is done by value or by index, LinkedList has to potentially scan the entire list first to find the element(s) to be deleted.

If it means move some elements back and then put the element in the middle empty spot, ArrayList should be slower.

Yes, this is what it means. ArrayList is indeed slower than LinkedList because it has to free up a slot in the middle of the array. This involves moving some references around and in the worst case reallocating the entire array. LinkedList just has to manipulate some references.

Multiple conditions in if statement shell script

You are trying to compare strings inside an arithmetic command (((...))). Use [[ instead.

if [[ $username == "$username1" && $password == "$password1" ]] ||
   [[ $username == "$username2" && $password == "$password2" ]]; then

Note that I've reduced this to two separate tests joined by ||, with the && moved inside the tests. This is because the shell operators && and || have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d is equivalent to the intended ( a && b ) || ( c && d ).

Python division

Personally I preferred to insert a 1. * at the very beginning. So the expression become something like this:

1. * (20-10) / (100-10)

As I always do a division for some formula like:

accuracy = 1. * (len(y_val) - sum(y_val)) / len(y_val)

so it is impossible to simply add a .0 like 20.0. And in my case, wrapping with a float() may lose a little bit readability.

What is HTTP "Host" header?

The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).


Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

GET /someresource.html HTTP/1.1
Host: www.example.com

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.

Aligning rotated xticklabels with their respective xticks

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

plt.xticks(rotation=45)

How to add a RequiredFieldValidator to DropDownList control?

InitialValue="0" : initial validation will fire when 0th index item is selected in ddl.

<asp:RequiredFieldValidator InitialValue="0" Display="Dynamic" CssClass="error" runat="server" ID="your_id" ValidationGroup="validationgroup" ControlToValidate="your_dropdownlist_id" />

Error handling in AngularJS http get then construct

Try this

function sendRequest(method, url, payload, done){

        var datatype = (method === "JSONP")? "jsonp" : "json";
        $http({
                method: method,
                url: url,
                dataType: datatype,
                data: payload || {},
                cache: true,
                timeout: 1000 * 60 * 10
        }).then(
            function(res){
                done(null, res.data); // server response
            },
            function(res){
                responseHandler(res, done);
            }
        );

    }
    function responseHandler(res, done){
        switch(res.status){
            default: done(res.status + ": " + res.statusText);
        }
    }

What does java.lang.Thread.interrupt() do?

What is interrupt ?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

How is it implemented ?

The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static Thread.isInterrupted, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

Quote from Thread.interrupt() API:

Interrupts this thread. First the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

If none of the previous conditions hold then this thread's interrupt status will be set.

Check this out for complete understanding about same :

http://download.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

How to sort ArrayList<Long> in decreasing order?

A more general approach to implement our own Comparator as below

Collections.sort(lst,new Comparator<Long>(){
                public int compare(Long o1, Long o2) {
                    return o2.compareTo(o1);
                }
            });

Should I use Java's String.format() if performance is important?

Another perspective from Logging point of view Only.

I see a lot of discussion related to logging on this thread so thought of adding my experience in answer. May be someone will find it useful.

I guess the motivation of logging using formatter comes from avoiding the string concatenation. Basically, you do not want to have an overhead of string concat if you are not going to log it.

You do not really need to concat/format unless you want to log. Lets say if I define a method like this

public void logDebug(String... args, Throwable t) {
    if(debugOn) {
       // call concat methods for all args
       //log the final debug message
    }
}

In this approach the cancat/formatter is not really called at all if its a debug message and debugOn = false

Though it will still be better to use StringBuilder instead of formatter here. The main motivation is to avoid any of that.

At the same time I do not like adding "if" block for each logging statement since

  • It affects readability
  • Reduces coverage on my unit tests - thats confusing when you want to make sure every line is tested.

Therefore I prefer to create a logging utility class with methods like above and use it everywhere without worrying about performance hit and any other issues related to it.