Programs & Examples On #Shortest path

Shortest path problems are problems addressing finding the shortest path from a single source to a target source, usually in a graph.

How does a Breadth-First Search work when looking for Shortest Path?

I have wasted 3 days
ultimately solved a graph question
used for
finding shortest distance
using BFS

Want to share the experience.

When the (undirected for me) graph has
fixed distance (1, 6, etc.) for edges

#1
We can use BFS to find shortest path simply by traversing it
then, if required, multiply with fixed distance (1, 6, etc.)

#2
As noted above
with BFS
the very 1st time an adjacent node is reached, it is shortest path

#3
It does not matter what queue you use
   deque/queue(c++) or
   your own queue implementation (in c language)
   A circular queue is unnecessary

#4
Number of elements required for queue is N+1 at most, which I used
(dint check if N works)
here, N is V, number of vertices.

#5
Wikipedia BFS will work, and is sufficient.
    https://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode

I have lost 3 days trying all above alternatives, verifying & re-verifying again and again above
they are not the issue.
(Try to spend time looking for other issues, if you dint find any issues with above 5).


More explanation from the comment below:

      A
     /  \
  B       C
 /\       /\
D  E     F  G

Assume above is your graph
graph goes downwards
For A, the adjacents are B & C
For B, the adjacents are D & E
For C, the adjacents are F & G

say, start node is A

  1. when you reach A, to, B & C the shortest distance to B & C from A is 1

  2. when you reach D or E, thru B, the shortest distance to A & D is 2 (A->B->D)

similarly, A->E is 2 (A->B->E)

also, A->F & A->G is 2

So, now instead of 1 distance between nodes, if it is 6, then just multiply the answer by 6
example,
if distance between each is 1, then A->E is 2 (A->B->E = 1+1)
if distance between each is 6, then A->E is 12 (A->B->E = 6+6)

yes, bfs may take any path
but we are calculating for all paths

if you have to go from A to Z, then we travel all paths from A to an intermediate I, and since there will be many paths we discard all but shortest path till I, then continue with shortest path ahead to next node J
again if there are multiple paths from I to J, we only take shortest one
example,
assume,
A -> I we have distance 5
(STEP) assume, I -> J we have multiple paths, of distances 7 & 8, since 7 is shortest
we take A -> J as 5 (A->I shortest) + 8 (shortest now) = 13
so A->J is now 13
we repeat now above (STEP) for J -> K and so on, till we get to Z

Read this part, 2 or 3 times, and draw on paper, you will surely get what i am saying, best of luck


Negative weights using Dijkstra's Algorithm

Since Dijkstra is a Greedy approach, once a vertice is marked as visited for this loop, it would never be reevaluated again even if there's another path with less cost to reach it later on. And such issue could only happen when negative edges exist in the graph.


A greedy algorithm, as the name suggests, always makes the choice that seems to be the best at that moment. Assume that you have an objective function that needs to be optimized (either maximized or minimized) at a given point. A Greedy algorithm makes greedy choices at each step to ensure that the objective function is optimized. The Greedy algorithm has only one shot to compute the optimal solution so that it never goes back and reverses the decision.

Why doesn't Dijkstra's algorithm work for negative weight edges?

Recall that in Dijkstra's algorithm, once a vertex is marked as "closed" (and out of the open set) - the algorithm found the shortest path to it, and will never have to develop this node again - it assumes the path developed to this path is the shortest.

But with negative weights - it might not be true. For example:

       A
      / \
     /   \
    /     \
   5       2
  /         \
  B--(-10)-->C

V={A,B,C} ; E = {(A,C,2), (A,B,5), (B,C,-10)}

Dijkstra from A will first develop C, and will later fail to find A->B->C


EDIT a bit deeper explanation:

Note that this is important, because in each relaxation step, the algorithm assumes the "cost" to the "closed" nodes is indeed minimal, and thus the node that will next be selected is also minimal.

The idea of it is: If we have a vertex in open such that its cost is minimal - by adding any positive number to any vertex - the minimality will never change.
Without the constraint on positive numbers - the above assumption is not true.

Since we do "know" each vertex which was "closed" is minimal - we can safely do the relaxation step - without "looking back". If we do need to "look back" - Bellman-Ford offers a recursive-like (DP) solution of doing so.

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

PostgreSQL: How to make "case-insensitive" query

You can also read up on the ILIKE keyword. It can be quite useful at times, albeit it does not conform to the SQL standard. See here for more information: http://www.postgresql.org/docs/9.2/static/functions-matching.html

Create database from command line

createdb is a command line utility which you can run from bash and not from psql. To create a database from psql, use the create database statement like so:

create database [databasename];

Note: be sure to always end your SQL statements with ;

Java 8 Lambda function that throws exception?

I had this problem with Class.forName and Class.newInstance inside a lambda, so I just did:

public Object uncheckedNewInstanceForName (String name) {

    try {
        return Class.forName(name).newInstance();
    }
    catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

Inside the lambda, instead of calling Class.forName("myClass").newInstance() I just called uncheckedNewInstanceForName ("myClass")

django templates: include and extends

Added for reference to future people who find this via google: You might want to look at the {% overextend %} tag provided by the mezzanine library for cases like this.

How to subtract X day from a Date object in Java?

Java 8 and later

With Java 8's date time API change, Use LocalDate

LocalDate date = LocalDate.now().minusDays(300);

Similarly you can have

LocalDate date = someLocalDateInstance.minusDays(300);

Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Java 7 and earlier

Use Calendar's add() method

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();

MemoryStream - Cannot access a closed Stream

This is because the StreamReader closes the underlying stream automatically when being disposed of. The using statement does this automatically.

However, the StreamWriter you're using is still trying to work on the stream (also, the using statement for the writer is now trying to dispose of the StreamWriter, which is then trying to close the stream).

The best way to fix this is: don't use using and don't dispose of the StreamReader and StreamWriter. See this question.

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);
    var sr = new StreamReader(ms);

    sw.WriteLine("data");
    sw.WriteLine("data 2");
    ms.Position = 0;

    Console.WriteLine(sr.ReadToEnd());                        
}

If you feel bad about sw and sr being garbage-collected without being disposed of in your code (as recommended), you could do something like that:

StreamWriter sw = null;
StreamReader sr = null;

try
{
    using (var ms = new MemoryStream())
    {
        sw = new StreamWriter(ms);
        sr = new StreamReader(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;

        Console.WriteLine(sr.ReadToEnd());                        
    }
}
finally
{
    if (sw != null) sw.Dispose();
    if (sr != null) sr.Dispose();
}

What is JavaScript garbage collection?

To the best of my knowledge, JavaScript's objects are garbage collected periodically when there are no references remaining to the object. It is something that happens automatically, but if you want to see more about how it works, at the C++ level, it makes sense to take a look at the WebKit or V8 source code

Typically you don't need to think about it, however, in older browsers, like IE 5.5 and early versions of IE 6, and perhaps current versions, closures would create circular references that when unchecked would end up eating up memory. In the particular case that I mean about closures, it was when you added a JavaScript reference to a dom object, and an object to a DOM object that referred back to the JavaScript object. Basically it could never be collected, and would eventually cause the OS to become unstable in test apps that looped to create crashes. In practice these leaks are usually small, but to keep your code clean you should delete the JavaScript reference to the DOM object.

Usually it is a good idea to use the delete keyword to immediately de-reference big objects like JSON data that you have received back and done whatever you need to do with it, especially in mobile web development. This causes the next sweep of the GC to remove that object and free its memory.

How are parameters sent in an HTTP POST request?

The values are sent in the request body, in the format that the content type specifies.

Usually the content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string:

parameter=value&also=another

When you use a file upload in the form, you use the multipart/form-data encoding instead, which has a different format. It's more complicated, but you usually don't need to care what it looks like, so I won't show an example, but it can be good to know that it exists.

How to bind an enum to a combobox control in WPF?

Use ObjectDataProvider:

<ObjectDataProvider x:Key="enumValues"
   MethodName="GetValues" ObjectType="{x:Type System:Enum}">
      <ObjectDataProvider.MethodParameters>
           <x:Type TypeName="local:ExampleEnum"/>
      </ObjectDataProvider.MethodParameters>
 </ObjectDataProvider>

and then bind to static resource:

ItemsSource="{Binding Source={StaticResource enumValues}}"

based on this article

Is there a naming convention for MySQL?

as @fabrizio-valencia said use lower case. in windows if you export mysql database (phpmyadmin) the tables name will converted to lower case and this lead to all sort of problems. see Are table names in MySQL case sensitive?

How to sort an array based on the length of each element?

I adapted @shareef's answer to make it concise. I use,

.sort(function(arg1, arg2) { return arg1.length - arg2.length })

MySQL error: key specification without a key length

I got this error when adding an index to a table with text type columns. You need to declare the size amount you want to use for each text type.

Put the size amount within the parenthesis ( )

If too many bytes are used you can declare a size in the brackets for varchar to decrease the amount used for indexing. This is even if you declared a size for a type already like varchar(1000). You don't need to create a new table like others have said.

Adding index

alter table test add index index_name(col1(255),col2(255));

Adding unique index

alter table test add unique index_name(col1(255),col2(255));

How do I prevent the padding property from changing width or height in CSS?

when I add the padding-left property, the width of the DIV changes to 220px

Yes, that is exactly according to the standards. That's how it's supposed to work.

Let's say I create another DIV named anotherdiv exactly the same as newdiv, and put it inside of newdiv but newdiv has no padding and anotherdiv has padding-left: 20px. I get the same thing, newdiv's width will be 220px;

No, newdiv will remain 200px wide.

How to increase Java heap space for a tomcat app

Just set this extra line in catalina.bat file

LINE NO AROUND: 143

set "CATALINA_OPTS=-Xms512m -Xmx512m"

And restart Tomcat service

CSS3 scrollbar styling on a div

You're setting overflow: hidden. This will hide anything that's too large for the <div>, meaning scrollbars won't be shown. Give your <div> an explicit width and/or height, and change overflow to auto:

.scroll {
   width: 200px;
   height: 400px;
   overflow: scroll;
}

If you only want to show a scrollbar if the content is longer than the <div>, change overflow to overflow: auto. You can also only show one scrollbar by using overflow-y or overflow-x.

How to show the text on a ImageButton?

It is technically possible to put a caption on an ImageButton if you really want to do it. Just put a TextView over the ImageButton using FrameLayout. Just remember to not make the Textview clickable.

Example:

<FrameLayout>
    <ImageButton
        android:id="@+id/button_x"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@null"
        android:scaleType="fitXY"
        android:src="@drawable/button_graphic" >
    </ImageButton>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:clickable="false"
        android:text="TEST TEST" >
    </TextView>
</FrameLayout>

Avoid dropdown menu close on click inside

I've got a similar problem recently and tried different ways to solve it with removing the data attribute data-toggle="dropdown" and listening click with event.stopPropagation() calling.

The second way looks more preferable. Also Bootstrap developers use this way. In the source file I found initialization of the dropdown elements:

// APPLY TO STANDARD DROPDOWN ELEMENTS
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
}(jQuery);

So, this line:

.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })

suggests you can put a form element inside the container with class .dropdown to avoid closing the dropdown menu.

How to run a jar file in a linux commandline

For OpenSuse Linux, One can simply install the java-binfmt package in the zypper repository as shown below:

sudo zypper in java-binfmt-misc
chmod 755 file.jar
./file.jar

Understanding string reversal via slicing

the first two bounds default to 0 and the length of the sequence, as before, and a stride of -1 indicates that the slice should go from right to left instead of the usual left to right. The effect, therefore, is to reverse the sequence.

name="ravi"
print(name[::-1]) #ivar

javascript create array from for loop

even shorter if you can lose the yearStart value:

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

while(yearStart < yearEnd+1){
  arr.push(yearStart++);
}

UPDATE: If you can use the ES6 syntax you can do it the way proposed here:

let yearStart = 2000;
let yearEnd = 2040;
let years = Array(yearEnd-yearStart+1)
    .fill()
    .map(() => yearStart++);

How do I concatenate two arrays in C#?

I settled on a more general-purpose solution that allows concatenating an arbitrary set of one-dimensional arrays of the same type. (I was concatenating 3+ at a time.)

My function:

    public static T[] ConcatArrays<T>(params T[][] list)
    {
        var result = new T[list.Sum(a => a.Length)];
        int offset = 0;
        for (int x = 0; x < list.Length; x++)
        {
            list[x].CopyTo(result, offset);
            offset += list[x].Length;
        }
        return result;
    }

And usage:

        int[] a = new int[] { 1, 2, 3 };
        int[] b = new int[] { 4, 5, 6 };
        int[] c = new int[] { 7, 8 };
        var y = ConcatArrays(a, b, c); //Results in int[] {1,2,3,4,5,6,7,8}

How to display an unordered list in two columns?

With Bootstrap... This answer (https://stackoverflow.com/a/23005046/1128742) got me pointed towards this solution:

<ul class="list-unstyled row">
   <li class="col-xs-6">Item 1</li>
   <li class="col-xs-6">Item 2</li>
   <li class="col-xs-6">Item 3</li>
</ul>

http://jsfiddle.net/patrickbad767/472r0ynf/

Is there a combination of "LIKE" and "IN" in SQL?

I would suggest using a TableValue user function if you'd like to encapsulate the Inner Join or temp table techniques shown above. This would allow it to read a bit more clearly.

After using the split function defined at: http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx

we can write the following based on a table I created called "Fish" (int id, varchar(50) Name)

SELECT Fish.* from Fish 
    JOIN dbo.Split('%ass,%e%',',') as Splits 
    on Name like Splits.items  //items is the name of the output column from the split function.

Outputs

1   Bass
2   Pike
7   Angler
8   Walleye

Best way to restrict a text field to numbers only?

You can make changes to accept the keycode for Ctrl keys: 17, 18, 19, 20. Then your code will be like:

function numbersonly(e, decimal) {
var key;
var keychar;

if (window.event) 
    key = window.event.keyCode;
else if (e) 
    key = e.which;
else 
    return true;

keychar = String.fromCharCode(key);

if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) || (key==17) || (key==18) || (key==19) || (key==20))
   return true;     
else if ((("0123456789").indexOf(keychar) > -1))
   return true;
else if (decimal && (keychar == "."))
   return true;        
else
   return false;
}

Generate GUID in MySQL for existing Data?

I faced mostly the same issue. Im my case uuid is stored as BINARY(16) and has NOT NULL UNIQUE constraints. And i faced with the issue when the same UUID was generated for every row, and UNIQUE constraint does not allow this. So this query does not work:

UNHEX(REPLACE(uuid(), '-', ''))

But for me it worked, when i used such a query with nested inner select:

UNHEX(REPLACE((SELECT uuid()), '-', ''))

Then is produced unique result for every entry.

How to use jQuery Plugin with Angular 4?

Install jQuery using NPM Jquery NPM

npm install jquery

Install the jQuery declaration file

npm install -D @types/jquery

Import jQuery inside .ts

import * as $ from 'jquery';

call inside class

export class JqueryComponent implements OnInit {

constructor() {
}

ngOnInit() {
    $(window).click(function () {
        alert('ok');
        });
    }

}

How Do I Upload Eclipse Projects to GitHub?

Many of these answers mention how to share the project on Git, which is easy, you just share the code on git, but one thing to take note of is that there is no apparent "project file" that the end user can double click on. Instead you have to use Import->General->Existing project and select the whole folder

Remove Item in Dictionary based on Value

Are you trying to remove a single value or all matching values?

If you are trying to remove a single value, how do you define the value you wish to remove?

The reason you don't get a key back when querying on values is because the dictionary could contain multiple keys paired with the specified value.

If you wish to remove all matching instances of the same value, you can do this:

foreach(var item in dic.Where(kvp => kvp.Value == value).ToList())
{
    dic.Remove(item.Key);
}

And if you wish to remove the first matching instance, you can query to find the first item and just remove that:

var item = dic.First(kvp => kvp.Value == value);

dic.Remove(item.Key);

Note: The ToList() call is necessary to copy the values to a new collection. If the call is not made, the loop will be modifying the collection it is iterating over, causing an exception to be thrown on the next attempt to iterate after the first value is removed.

Is there possibility of sum of ArrayList without looping

The only alternative to using a loop is to use recursion.

You can define a method like

public static int sum(List<Integer> ints) {
   return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());
}

This is very inefficient compared to using a plain loop and can blow up if you have many elements in the list.

An alternative which avoid a stack overflow is to use.

public static int sum(List<Integer> ints) {
    int len = ints.size();
    if (len == 0) return 0;
    if (len == 1) return ints.get(0);
    return sum(ints.subList(0, len/2)) + sum(ints.subList(len/2, len));
}

This is just as inefficient, but will avoid a stack overflow.


The shortest way to write the same thing is

int sum = 0, a[] = {2, 4, 6, 8};

for(int i: a) {
    sum += i;
}

System.out.println("sum(a) = " + sum);

prints

sum(a) = 20

How to set xampp open localhost:8080 instead of just localhost

I agree and found this file under xammp-control the type of file is configuration. When I changed it to 8080 it worked automagically!

AngularJS does not send hidden field value

update @tymeJV 's answer eg:

 <div style="display: none">
    <input type="text" name='price' ng-model="price" ng-init="price = <%= @product.price.to_s %>" >
 </div>

Git copy file preserving history

This process preserve history, but is little workarround:

# make branchs to new files
$: git mv arquivos && git commit

# in original branch, remove original files
$: git rm arquivos && git commit

# do merge and fix conflicts
$: git merge branch-copia-arquivos

# back to original branch and revert commit removing files
$: git revert commit

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

You could add it:

public static IEnumerable<T> OrderBy( this IEnumerable<T> input, string queryString) {
    //parse the string into property names
    //Use reflection to get and sort by properties
    //something like

    foreach( string propname in queryString.Split(','))
        input.OrderBy( x => GetPropertyValue( x, propname ) );

    // I used Kjetil Watnedal's reflection example
}

The GetPropertyValue function is from Kjetil Watnedal's answer

The issue would be why? Any such sort would throw exceptions at run-time, rather than compile time (like D2VIANT's answer).

If you're dealing with Linq to Sql and the orderby is an expression tree it will be converted into SQL for execution anyway.

Automatically deleting related rows in Laravel (Eloquent ORM)

I would iterate through the collection detaching everything before deleting the object itself.

here's an example:

try {
        $user = User::findOrFail($id);
        if ($user->has('photos')) {
            foreach ($user->photos as $photo) {

                $user->photos()->detach($photo);
            }
        }
        $user->delete();
        return 'User deleted';
    } catch (Exception $e) {
        dd($e);
    }

I know it is not automatic but it is very simple.

Another simple approach would be to provide the model with a method. Like this:

public function detach(){
       try {
            
            if ($this->has('photos')) {
                foreach ($this->photos as $photo) {
    
                    $this->photos()->detach($photo);
                }
            }
           
        } catch (Exception $e) {
            dd($e);
        }
}

Then you can simply call this where you need:

$user->detach();
$user->delete();

How do I disable right click on my web page?

You cannot accomplish what you're asking without using Javascript. Any other technology you may choose to use can only help to compose the web page on the server side to be sent to the browser.

There simply is no good solution, and there is no solution period without Javascript.

Remote Linux server to remote linux server dir copy. How?

As non-root user ideally:

scp -r src $host:$path

If you already some of the content on $host consider using rsync with ssh as a tunnel.

/Allan

How to change CSS using jQuery?

Ignore the people that are suggesting that the property name is the issue. The jQuery API documentation explicitly states that either notation is acceptable: http://api.jquery.com/css/

The actual problem is that you are missing a closing curly brace on this line:

$("#myParagraph").css({"backgroundColor":"black","color":"white");

Change it to this:

$("#myParagraph").css({"backgroundColor": "black", "color": "white"});

Here's a working demo: http://jsfiddle.net/YPYz8/

_x000D_
_x000D_
$(init);_x000D_
    _x000D_
function init() {_x000D_
    $("h1").css("backgroundColor", "yellow");_x000D_
    $("#myParagraph").css({ "backgroundColor": "black", "color": "white" });_x000D_
    $(".bordered").css("border", "1px solid black");_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<div class="bordered">_x000D_
    <h1>Header</h1>_x000D_
    <p id="myParagraph">This is some paragraph text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

regular expression for anything but an empty string

Assertions are not necessary for this. \S should work by itself as it matches any non-whitespace.

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

As far as I am aware, the MSVCRxxx.dlls are in %SystemRoot%\System32 (usually C:\Windows\System32).

The xxx refers to the version of the MS Visual C Runtime (hence MSVCR...)

However, the complication seems to be that the xxx version is not the same as the two digits of the year "version".

For example, Visual C Runtime 2013 yields MSVCR120.dll and "...Runtime 2012" yields MSVCR110.dll. And then Microsoft packages these as vcredist_x86.exe or vcredist_x64.exe, seemingly irrespective of the xxx version or the Visual Studio version number (2012, 2013 etc) - confused? You have every right to be!

So, firstly, you need to determine whether you need 32 bit, 64 bit or even both (some PHP distributions apparently do need both), then download the relevant vcredist... for the bits AND for the Visual Studio version. As far as I can tell, the only way to tell which vcredist... you have is to start to install it. Recent versions give an intro screen that quotes the Visual Studio version and the xxx version. I have renamed by vcredists to something like vcredist_x64_2012_V11.exe.

[EDIT] Forgot to add earlier that if you are simply looking to "install" the missing DLL (as opposed to resolve some bigger set of issues), then you probably won't do any harm by simply installing the relevant vcredist for your architecture (32 bit, 64 bit) and "missing" version.

Remove all unused resources from an android project

Beware if you are using multiple flavours when running lint. Lint may give false unused resources depending on the flavour you have selected.

Import an existing git project into GitLab?

rake gitlab:import:repos might be a more suitable method for mass importing:

  • copy the bare repository under repos_path (/home/git/repositories/group/repo.git). Directory name must end in .git and be under a group or user namespace.
  • run bundle exec rake gitlab:import:repos

The owner will the first admin, and a group will get created if not already existent.

See also: How to import an existing bare git repository into Gitlab?

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

Best C# API to create PDF

Update:

I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.


I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.

There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com

Editor does not contain a main type

A simpler way is to close the project and reopen it.

How to pass boolean parameter value in pipeline to downstream jobs?

Assuming

value: update_composer

was the issue, try

value: Boolean.valueOf(update_composer)

is there a less cumbersome way in which I can just pass ALL the pipeline parameters to the downstream job

Not that I know of, at least not without using Jenkins API calls and disabling the Groovy sandbox.

Disable browser 'Save Password' functionality

Because autocomplete="off" does not work for password fields, one must rely on javascript. Here's a simple solution based on answers found here.

Add the attribute data-password-autocomplete="off" to your password field:

<input type="password" data-password-autocomplete="off">

Include the following JS:

$(function(){
    $('[data-password-autocomplete="off"]').each(function() {
        $(this).prop('type', 'text');
        $('<input type="password"/>').hide().insertBefore(this);
        $(this).focus(function() {
            $(this).prop('type', 'password');
        });
    });     
});

This solution works for both Chrome and FF.

How to compare strings in an "if" statement?

You're looking for the function strcmp, or strncmp from string.h.

Since strings are just arrays, you need to compare each character, so this function will do that for you:

if (strcmp(favoriteDairyProduct, "cheese") == 0)
{
    printf("You like cheese too!");
}
else
{
    printf("I like cheese more.");
}

Further reading: strcmp at cplusplus.com

How to subtract 30 days from the current date using SQL Server

TRY THIS:

Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:

SELECT DATEADD(dd, -30, 
       CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21) 
       AS DATETIME))

REST API - Bulk Create or Update in single request

In a project I worked at we solved this problem by implement something we called 'Batch' requests. We defined a path /batch where we accepted json in the following format:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 5,
         binder: 8
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      }
   },
]

The response have the status code 207 (Multi-Status) and looks like this:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
      status: 200
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         error: {
            msg: 'A document with doc_number 5 already exists'
            ...
         }
      },
      status: 409
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      },
      status: 200
   },
]

You could also add support for headers in this structure. We implemented something that proved useful which was variables to use between requests in a batch, meaning we can use the response from one request as input to another.

Facebook and Google have similar implementations:
https://developers.google.com/gmail/api/guides/batch
https://developers.facebook.com/docs/graph-api/making-multiple-requests

When you want to create or update a resource with the same call I would use either POST or PUT depending on the case. If the document already exist, do you want the entire document to be:

  1. Replaced by the document you send in (i.e. missing properties in request will be removed and already existing overwritten)?
  2. Merged with the document you send in (i.e. missing properties in request will not be removed and already existing properties will be overwritten)?

In case you want the behavior from alternative 1 you should use a POST and in case you want the behavior from alternative 2 you should use PUT.

http://restcookbook.com/HTTP%20Methods/put-vs-post/

As people already suggested you could also go for PATCH, but I prefer to keep API's simple and not use extra verbs if they are not needed.

Best way to deploy Visual Studio application that can run without installing

It is possible and is deceptively easy:

  1. "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
  2. But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj).
  3. Zip that folder (leave out any *.vhost.* files and the app.publish folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.

An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.

It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.

Best practice for partial updates in a RESTful service

It doesn't matter. In terms of REST, you can't do a GET, because it's not cacheable, but it doesn't matter if you use POST or PATCH or PUT or whatever, and it doesn't matter what the URL looks like. If you're doing REST, what matters is that when you get a representation of your resource from the server, that representation is able give the client state transition options.

If your GET response had state transitions, the client just needs to know how to read them, and the server can change them if needed. Here an update is done using POST, but if it was changed to PATCH, or if the URL changes, the client still knows how to make an update:

{
  "customer" :
  {
  },
  "operations":
  [
    "update" : 
    {
      "method": "POST",
      "href": "https://server/customer/123/"
    }]
}

You could go as far as to list required/optional parameters for the client to give back to you. It depends on the application.

As far as business operations, that might be a different resource linked to from the customer resource. If you want to send an email to the customer, maybe that service is it's own resource that you can POST to, so you might include the following operation in the customer resource:

"email":
{
  "method": "POST",
  "href": "http://server/emailservice/send?customer=1234"
}

Some good videos, and example of the presenter's REST architecture are these. Stormpath only uses GET/POST/DELETE, which is fine since REST has nothing to do with what operations you use or how URLs should look (except GETs should be cacheable):

https://www.youtube.com/watch?v=pspy1H6A3FM,
https://www.youtube.com/watch?v=5WXYw4J4QOU,
http://docs.stormpath.com/rest/quickstart/

What port is used by Java RMI connection?

RMI generally won't work over a firewall, since it uses unpredictable ports (it starts off on 1099, and then runs off with a random port after that).

In these situations, you generally need to resort to tunnelling RMI over HTTP, which is described well here.

How to find encoding of a file via script on Linux?

If you're talking about XML-files (ISO-8859-1), the XML-declaration inside them specifies the encoding: <?xml version="1.0" encoding="ISO-8859-1" ?>
So, you can use regular expressions (e.g. with perl) to check every file for such specification.
More information can be found here: How to Determine Text File Encoding.

In Python, is there an elegant way to print a list in a custom format without explicit looping?

Take a look on pprint, The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable. This may be the case if objects such as files, sockets or classes are included, as well as many other objects which are not representable as Python literals.

>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff[:])
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(stuff)
[   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
    'spam',
    'eggs',
    'lumberjack',
    'knights',
    'ni']
>>> pp = pprint.PrettyPrinter(width=41, compact=True)
>>> pp.pprint(stuff)
[['spam', 'eggs', 'lumberjack',
  'knights', 'ni'],
 'spam', 'eggs', 'lumberjack', 'knights',
 'ni']
>>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
... ('parrot', ('fresh fruit',))))))))
>>> pp = pprint.PrettyPrinter(depth=6)
>>> pp.pprint(tup)
('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))

How to read a .xlsx file using the pandas Library in iPython?

Assign spreadsheet filename to file

Load spreadsheet

Print the sheet names

Load a sheet into a DataFrame by name: df1

file = 'example.xlsx'
xl = pd.ExcelFile(file)
print(xl.sheet_names)
df1 = xl.parse('Sheet1')

What is the difference between OFFLINE and ONLINE index rebuild in SQL Server?

Online index rebuilds are less intrusive when it comes to locking tables. Offline rebuilds cause heavy locking of tables which can cause significant blocking issues for things that are trying to access the database while the rebuild takes place.

"Table locks are applied for the duration of the index operation [during an offline rebuild]. An offline index operation that creates, rebuilds, or drops a clustered, spatial, or XML index, or rebuilds or drops a nonclustered index, acquires a Schema modification (Sch-M) lock on the table. This prevents all user access to the underlying table for the duration of the operation. An offline index operation that creates a nonclustered index acquires a Shared (S) lock on the table. This prevents updates to the underlying table but allows read operations, such as SELECT statements."

http://msdn.microsoft.com/en-us/library/ms188388(v=sql.110).aspx

Additionally online index rebuilds are a enterprise (or developer) version only feature.

Convert file path to a file URI?

What no-one seems to realize is that none of the System.Uri constructors correctly handles certain paths with percent signs in them.

new Uri(@"C:\%51.txt").AbsoluteUri;

This gives you "file:///C:/Q.txt" instead of "file:///C:/%2551.txt".

Neither values of the deprecated dontEscape argument makes any difference, and specifying the UriKind gives the same result too. Trying with the UriBuilder doesn't help either:

new UriBuilder() { Scheme = Uri.UriSchemeFile, Host = "", Path = @"C:\%51.txt" }.Uri.AbsoluteUri

This returns "file:///C:/Q.txt" as well.

As far as I can tell the framework is actually lacking any way of doing this correctly.

We can try to it by replacing the backslashes with forward slashes and feed the path to Uri.EscapeUriString - i.e.

new Uri(Uri.EscapeUriString(filePath.Replace(Path.DirectorySeparatorChar, '/'))).AbsoluteUri

This seems to work at first, but if you give it the path C:\a b.txt then you end up with file:///C:/a%2520b.txt instead of file:///C:/a%20b.txt - somehow it decides that some sequences should be decoded but not others. Now we could just prefix with "file:///" ourselves, however this fails to take UNC paths like \\remote\share\foo.txt into account - what seems to be generally accepted on Windows is to turn them into pseudo-urls of the form file://remote/share/foo.txt, so we should take that into account as well.

EscapeUriString also has the problem that it does not escape the '#' character. It would seem at this point that we have no other choice but making our own method from scratch. So this is what I suggest:

public static string FilePathToFileUrl(string filePath)
{
  StringBuilder uri = new StringBuilder();
  foreach (char v in filePath)
  {
    if ((v >= 'a' && v <= 'z') || (v >= 'A' && v <= 'Z') || (v >= '0' && v <= '9') ||
      v == '+' || v == '/' || v == ':' || v == '.' || v == '-' || v == '_' || v == '~' ||
      v > '\xFF')
    {
      uri.Append(v);
    }
    else if (v == Path.DirectorySeparatorChar || v == Path.AltDirectorySeparatorChar)
    {
      uri.Append('/');
    }
    else
    {
      uri.Append(String.Format("%{0:X2}", (int)v));
    }
  }
  if (uri.Length >= 2 && uri[0] == '/' && uri[1] == '/') // UNC path
    uri.Insert(0, "file:");
  else
    uri.Insert(0, "file:///");
  return uri.ToString();
}

This intentionally leaves + and : unencoded as that seems to be how it's usually done on Windows. It also only encodes latin1 as Internet Explorer can't understand unicode characters in file urls if they are encoded.

How to get the last N rows of a pandas DataFrame?

How to get the last N rows of a pandas DataFrame?

If you are slicing by position, __getitem__ (i.e., slicing with[]) works well, and is the most succinct solution I've found for this problem.

pd.__version__
# '0.24.2'

df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df

   A  B
0  a  1
1  a  2
2  a  3
3  b  4
4  b  5
5  b  6
6  b  7
7  c  8

df[-3:]

   A  B
5  b  6
6  b  7
7  c  8

This is the same as calling df.iloc[-3:], for instance (iloc internally delegates to __getitem__).


As an aside, if you want to find the last N rows for each group, use groupby and GroupBy.tail:

df.groupby('A').tail(2)

   A  B
1  a  2
2  a  3
5  b  6
6  b  7
7  c  8

Using new line(\n) in string and rendering the same in HTML

I had the following problem where I was fetching data from a database and wanted to display a string containing \n. None of the solutions above worked for me and I finally came up with a solution: https://stackoverflow.com/a/61484190/7251208

How can I convert a zero-terminated byte array to string?

Simplistic solution:

str := fmt.Sprintf("%s", byteArray)

I'm not sure how performant this is though.

MySQL selecting yesterday's date

You can use:

SELECT SUBDATE(NOW(), 1);

or

SELECT SUBDATE(NOW(), INTERVAL 1 DAY);

or

SELECT NOW() - INTERVAL 1 DAY;

or

SELECT DATE_SUB(NOW(), INTERVAL 1 DAY);

How to use template module with different set of variables?

This is a solution/hack I'm using:

tasks/main.yml:

- name: parametrized template - a
  template:
    src: test.j2
    dest: /tmp/templateA
  with_items: var_a

- name: parametrized template - b
  template:
    src: test.j2
    dest: /tmp/templateB
  with_items: var_b

vars/main.yml

var_a:
  - 'this is var_a'
var_b:
  - 'this is var_b'

templates/test.j2:

{{ item }}

After running this, you get this is var_a in /tmp/templateA and this is var_b in /tmp/templateB.

Basically you abuse with_items to render the template with each item in the one-item list. This works because you can control what the list is when using with_items.

The downside of this is that you have to use item as the variable name in you template.

If you want to pass more than one variable this way, you can dicts as your list items like this:

var_a:
  -
    var_1: 'this is var_a1'
    var_2: 'this is var_a2'
var_b:
  -
    var_1: 'this is var_b1'
    var_2: 'this is var_b2'

and then refer to them in your template like this:

{{ item.var_1 }}
{{ item.var_2 }}

Get the Query Executed in Laravel 3/4

Laravel 3

Another way to do this is:

#config/database.php

'profiler' => true

For all Queries result:

print_r(DB::profiler());

For last Result:

print_r(DB::last_query());

How to recompile with -fPIC

Have a look at this page.

you can try globally adding the flag using: export CXXFLAGS="$CXXFLAGS -fPIC"

convert NSDictionary to NSString

You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:

[NSString stringWithFormat:@"my dictionary is %@", aDictionary];

or

NSLog(@"My dictionary is %@", aDictionary);

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

Shell Script — Get all files modified after <date>

You can get a list of files last modified later than x days ago with:

find . -mtime -x

Then you just have to tar and zip files in the resulting list, e.g.:

tar czvf mytarfile.tgz `find . -mtime -30`

for all files modified during last month.

SQL Server equivalent of MySQL's NOW()?

getdate() 

is the direct equivalent, but you should always use UTC datetimes

getutcdate()

whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions

Install MySQL on Ubuntu without a password prompt

Another way to make it work:

echo "mysql-server-5.5 mysql-server/root_password password root" | debconf-set-selections
echo "mysql-server-5.5 mysql-server/root_password_again password root" | debconf-set-selections
apt-get -y install mysql-server-5.5

Note that this simply sets the password to "root". I could not get it to set a blank password using simple quotes '', but this solution was sufficient for me.

Based on a solution here.

How to use CMAKE_INSTALL_PREFIX

But do remember to place it BEFORE PROJECT(< project_name>) command, otherwise it will not work!

My first week of using cmake - after some years of GNU autotools - so I am still learning (better then writing m4 macros), but I think modifying CMAKE_INSTALL_PREFIX after setting project is the better place.

CMakeLists.txt

cmake_minimum_required (VERSION 2.8)

set (CMAKE_INSTALL_PREFIX /foo/bar/bubba)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")
project (BarkBark)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")
set (CMAKE_INSTALL_PREFIX /foo/bar/bubba)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")

First run (no cache)

CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- The C compiler identification is GNU 4.4.7
-- etc, etc,...
CIP = /usr/local (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- Configuring done
-- Generating done

Second run

CIP = /foo/bar/bubba (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- Configuring done
-- Generating done

Let me know if I am mistaken, I have a lot of learning to do. It's fun.

javascript scroll event for iPhone/iPad?

For iOS you need to use the touchmove event as well as the scroll event like this:

document.addEventListener("touchmove", ScrollStart, false);
document.addEventListener("scroll", Scroll, false);

function ScrollStart() {
    //start of scroll event for iOS
}

function Scroll() {
    //end of scroll event for iOS
    //and
    //start/end of scroll event for other browsers
}

PHP prepend leading zero before single digit number, on-the-fly

The universal tool for string formatting, sprintf:

$stamp = sprintf('%s%02s', $year, $month);

http://php.net/manual/en/function.sprintf.php

XPath:: Get following Sibling

You can go for identifying a list of elements with xPath:

//td[text() = ' Color Digest ']/following-sibling::td[1]

This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:

List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))

Now, you can use the 2nd element as your intended element, which is elements.get(1)

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

Using Html.ActionLink to call action on different controller

try it it is working fine

  <%:Html.ActionLink("Details","Details","Product",  new {id=item.dateID },null)%>

How to access the value of a promise?

When a promise is resolved/rejected, it will call its success/error handler:

var promiseB = promiseA.then(function(result) {
   // do something with result
});

The then method also returns a promise: promiseB, which will be resolved/rejected depending on the return value from the success/error handler from promiseA.

There are three possible values that promiseA's success/error handlers can return that will affect promiseB's outcome:

1. Return nothing --> PromiseB is resolved immediately, 
   and undefined is passed to the success handler of promiseB
2. Return a value --> PromiseB is resolved immediately,
   and the value is passed to the success handler of promiseB
3. Return a promise --> When resolved, promiseB will be resolved. 
   When rejected, promiseB will be rejected. The value passed to
   the promiseB's then handler will be the result of the promise

Armed with this understanding, you can make sense of the following:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

The then call returns promiseB immediately. When promiseA is resolved, it will pass the result to promiseA's success handler. Since the return value is promiseA's result + 1, the success handler is returning a value (option 2 above), so promiseB will resolve immediately, and promiseB's success handler will be passed promiseA's result + 1.

How to hide navigation bar permanently in android activity?

Its a security issue: https://stackoverflow.com/a/12605313/1303691

therefore its not possible to hide the Navigation on a tablet permanently with one single call at the beginning of the view creation. It will be hidden, but it will pop up when touching the Screen. So just the second touch to your screen can cause a onClickEvent on your layout. Therefore you need to intercept this call, but i haven't managed it yet, i will update my answer when i found it out. Or do you now the answer already?

How to set or change the default Java (JDK) version on OS X?

I have done it for the local terminal with

export JAVA_8_HOME=(/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home/)
export JAVA_13_HOME=(/Library/Java/JavaVirtualMachines/jdk-13.0.1.jdk/Contents/Home/)

alias java8='export JAVA_HOME=$JAVA_8_HOME; alias java="$JAVA_8_HOME/bin/java"; $JAVA_8_HOME/bin/java -version'
alias java13='export JAVA_HOME=$JAVA_13_HOME; alias java="$JAVA_13_HOME/bin/java"; $JAVA_13_HOME/bin/java -version'

export JAVA_HOME=$JAVA_13_HOME

Import CSV file as a pandas DataFrame

pandas to the rescue:

import pandas as pd
print pd.read_csv('value.txt')

        Date    price  factor_1  factor_2
0  2012-06-11  1600.20     1.255     1.548
1  2012-06-12  1610.02     1.258     1.554
2  2012-06-13  1618.07     1.249     1.552
3  2012-06-14  1624.40     1.253     1.556
4  2012-06-15  1626.15     1.258     1.552
5  2012-06-16  1626.15     1.263     1.558
6  2012-06-17  1626.15     1.264     1.572

This returns pandas DataFrame that is similar to R's.

How to create nonexistent subdirectories recursively using Bash?

mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8

How to add app icon within phonegap projects?

In cordova 3.3.1-0.1.2 the expected behavior is not working right.

in

http://cordova.apache.org/docs/en/3.3.0/config_ref_images.md.html#Icons%20and%20Splash%20Screens

it clearly states you're suppose to put them into your main www folder in a folder called res and icons that follow a particular naming convention instead of the original customizable config.xml specified way (in which you point to a file of your choosing, which was/is much better). it should take then from there for each platform and put them into the platforms/?android?/res/drawable-?dpi/icon.png but it does no such correct behavior at this time... bug.

so I guess we have to manually put them there for each platform. it would of course need to remove that from duplicating it into the www folder again. for me I had to totally replace the contents in the main www folder anyway because it simply didn't work with even hello world without hacking a redirect index.html to find some weird random folder there. Putting the res folder beside www makes the most sense but what ever it seems to be for me caused by this series of cascading and confusing design choices/flaws.

How do I set ANDROID_SDK_HOME environment variable?

If you face the same error, here are the step by step instructions:

  1. Open control panel
  2. Then go to System
  3. Then go to Change Environment Variables of the User
  4. Then click create a new environment variables
  5. Create a new variable named ANDROID_SDK_HOME
  6. Set its value to your Android directory, like C:/users/<username>/.android

Random String Generator Returning Same String

My RandomString() method to generate a random string.

private static readonly Random _rand = new Random();

/// <summary>
/// Generate a random string.
/// </summary>
/// <param name="length">The length of random string. The minimum length is 3.</param>
/// <returns>The random string.</returns>
public string RandomString(int length)
{
    length = Math.Max(length, 3);

    byte[] bytes = new byte[length];
    _rand.NextBytes(bytes);
    return Convert.ToBase64String(bytes).Substring(0, length);
}

jQuery: select an element's class and id at the same time?

You can do:

$("#country.save")...

OR

$("a#country.save")...

OR

$("a.save#country")...

as you prefer.

So yes you can specify a selector that has to match ID and class (and potentially tag name and anything else you want to throw in).

Differences between .NET 4.0 and .NET 4.5 in High level in .NET

This answer may be late reply but it will be useful for seeing this topic in future.

The features of .NET framework 4.5 can be seen in the following link.

To summarize:

  • Installation

    .NET Framework 4.5 does not support Windows XP or Windows Server 2003, and therefore, if you have to create applications that target these operating systems, you will need to stay with .NET Framework 4.0. In contrast, Windows 8 and Windows Server 2012 in all of their editions include .NET Framework 4.5.

  • Support for Arrays Larger than 2 GB on 64-bit Platforms
  • Enhanced Background Server Garbage Collection
  • Support for Timeouts in Regular Expression Evaluations
  • Support for Unicode 6.0.0 in Culture-Sensitive Sorting and Casing Rules on Windows 8
  • Simple Default Culture Definition for an Application Domain
  • Internationalized Domain Names in Windows 8 Apps

package R does not exist

If you encounter this error in Android Studio:

Check the Gradle module file(s) -> defaultConfig -> applicationId setting.

Check the AndroidManifest.xml -> manifest package tag.

Check the package declarations in all src java files.

Sync, Clean then Rebuild with Gradle.

NEVER build your own R file. R is auto-generated from your source java files and build settings.

How do I view cookies in Internet Explorer 11 using Developer Tools

How about typing document.cookie into the console? It just shows the values, but it's something.

enter image description here

insert password into database in md5 format?

if you want to use md5 encryptioon you can do it in your php script

$pass = $_GET['pass'];

$newPass = md5($pass)

and then insert it into the database that way, however MD5 is a one way encryption method and is near on impossible to decrypt without difficulty

Assert an object is a specific type

Solution for JUnit 5

The documentation says:

However, JUnit Jupiter’s org.junit.jupiter.Assertions class does not provide an assertThat() method like the one found in JUnit 4’s org.junit.Assert class which accepts a Hamcrest Matcher. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.

Example for Hamcrest:

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class HamcrestAssertionDemo {

    @Test
    void assertWithHamcrestMatcher() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }

}

Example for AssertJ:

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class AssertJDemo {

    @Test
    void assertWithAssertJ() {
        SubClass subClass = new SubClass();
        assertThat(subClass).isInstanceOf(BaseClass.class);
    }

}

Note that this assumes you want to test behaviors similar to instanceof (which accepts subclasses). If you want exact equal type, I don’t see a better way than asserting the two class to be equal like you mentioned in the question.

Lua string to int

Use the tonumber function. As in a = tonumber("10").

Exception of type 'System.OutOfMemoryException' was thrown. Why?

Where does it fail?

I agree that your issue is probably that your dataset of 600,000 rows is probably just too large. I see that you are then adding it to Session. If you are using Sql session state, it will have to serialize that data as well.

Even if you dispose of your objects properly, you will always have at least 2 copies of this dataset in memory if you run it twice, once in session, once in procedural code. This will never scale in a web application.

Do the math, 600,000 rows, at even 1-128 bit guid per row would yield 9.6 megabytes (600k * 128 / 8) of just data, not to mention the dataset overhead.

Trim down your results.

How can I get the corresponding table header (th) from a table cell (td)?

Find matching th for a td, taking into account colspan index issues.

_x000D_
_x000D_
$('table').on('click', 'td', get_TH_by_TD)_x000D_
_x000D_
function get_TH_by_TD(e){_x000D_
   var idx = $(this).index(),_x000D_
       th, th_colSpan = 0;_x000D_
_x000D_
   for( var i=0; i < this.offsetParent.tHead.rows[0].cells.length; i++ ){_x000D_
      th = this.offsetParent.tHead.rows[0].cells[i];_x000D_
      th_colSpan += th.colSpan;_x000D_
      if( th_colSpan >= (idx + this.colSpan) )_x000D_
        break;_x000D_
   }_x000D_
   _x000D_
   console.clear();_x000D_
   console.log( th );_x000D_
   return th;_x000D_
}
_x000D_
table{ width:100%; }_x000D_
th, td{ border:1px solid silver; padding:5px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>Click a TD:</p>_x000D_
<table>_x000D_
    <thead> _x000D_
        <tr>_x000D_
            <th colspan="2"></th>_x000D_
            <th>Name</th>_x000D_
            <th colspan="2">Address</th>_x000D_
            <th colspan="2">Other</th>_x000D_
        </tr>_x000D_
    </thead> _x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>X</td>_x000D_
            <td>1</td>_x000D_
            <td>Jon Snow</td>_x000D_
            <td>12</td>_x000D_
            <td>High Street</td>_x000D_
            <td>Postfix</td>_x000D_
            <td>Public</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to use cURL to get jSON data and decode the data?

you can also use

$result = curl_exec($ch);
return response()->json(json_decode($result));

Can't stop rails server

Also, Make sure that you are doing command Cntrl+C in the same terminal (tab) which is used to start the server.

In my case, I had 2 tabs but i forgot to stop the server from correct tab and i was wondering why Cntrl+C is not working.

changing default x range in histogram matplotlib

plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')

Comparing object properties in c#

I think the answer of Big T was quite good but the deep comparison was missing, so I tweaked it a little bit:

using System.Collections.Generic;
using System.Reflection;

/// <summary>Comparison class.</summary>
public static class Compare
{
    /// <summary>Compare the public instance properties. Uses deep comparison.</summary>
    /// <param name="self">The reference object.</param>
    /// <param name="to">The object to compare.</param>
    /// <param name="ignore">Ignore property with name.</param>
    /// <typeparam name="T">Type of objects.</typeparam>
    /// <returns><see cref="bool">True</see> if both objects are equal, else <see cref="bool">false</see>.</returns>
    public static bool PublicInstancePropertiesEqual<T>(T self, T to, params string[] ignore) where T : class
    {
        if (self != null && to != null)
        {
            var type = self.GetType();
            var ignoreList = new List<string>(ignore);
            foreach (var pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (ignoreList.Contains(pi.Name))
                {
                    continue;
                }

                var selfValue = type.GetProperty(pi.Name).GetValue(self, null);
                var toValue = type.GetProperty(pi.Name).GetValue(to, null);

                if (pi.PropertyType.IsClass && !pi.PropertyType.Module.ScopeName.Equals("CommonLanguageRuntimeLibrary"))
                {
                    // Check of "CommonLanguageRuntimeLibrary" is needed because string is also a class
                    if (PublicInstancePropertiesEqual(selfValue, toValue, ignore))
                    {
                        continue;
                    }

                    return false;
                }

                if (selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue)))
                {
                    return false;
                }
            }

            return true;
        }

        return self == to;
    }
}

Printing 2D array in matrix format

Your can do it like this in short hands.

        int[,] values=new int[2,3]{{2,4,5},{4,5,2}};

        for (int i = 0; i < values.GetLength(0); i++)
        {
            for (int k = 0; k < values.GetLength(1); k++) {
                Console.Write(values[i,k]);
            }

            Console.WriteLine();
        }

JavaScript: IIF like statement

Something like this:

for (/* stuff */)
{
    var x = '<option value="' + col + '" '
        + (col === 'screwdriver' ? 'selected' : '')
        + '>Very roomy</option>';
    // snip...
}

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

I suspect that the jar files of hibernate-core and hibernate-entitymanager dependencies are corrupted or were not installed properly on your machine.

I suggest that you just delete the folders named hibernate-core and hibernate-entitymanager from your Maven local repository and Maven will reinstall them.

The default location for Maven local repository is C:\Documents and Settings\[USERNAME]\.m2 in windows or ~/.m2 in Linux/Mac.

Convert Dictionary<string,string> to semicolon separated string in c#

For Linq to work over Dictionary you need at least .Net v3.5 and using System.Linq;.

Some alternatives:

string myDesiredOutput = string.Join(";", myDict.Select(x => string.Join("=", x.Key, x.Value)));

or

string myDesiredOutput = string.Join(";", myDict.Select(x => $"{x.Key}={x.Value}"));

If you can't use Linq for some reason, use Stringbuilder:

StringBuilder sb = new StringBuilder();
var isFirst = true;
foreach(var x in myDict) 
{
  if (isFirst) 
  {
    sb.Append($"{x.Key}={x.Value}");
    isFirst = false;
  }
  else
    sb.Append($";{x.Key}={x.Value}"); 
}

string myDesiredOutput = sb.ToString(); 

myDesiredOutput:

A=1;B=2;C=3;D=4

Java 'file.delete()' Is not Deleting Specified File

Try closing all the FileOutputStream/FileInputStream you've opened earlier in other methods ,then try deleting ,worked like a charm.

How to access child's state in React?

Its 2020 and lots of you will come here looking for a similar solution but with Hooks ( They are great! ) and with latest approaches in terms of code cleanliness and syntax.

So as previous answers had stated, the best approach to this kind of problem is to hold the state outside of child component fieldEditor. You could do that in multiple ways.

The most "complex" is with global context (state) that both parent and children could access and modify. Its a great solution when components are very deep in the tree hierarchy and so its costly to send props in each level.

In this case I think its not worth it, and more simple approach will bring us the results we want, just using the powerful React.useState().

Approach with React.useState() hook, way simpler than with Class components

As said we will deal with changes and store the data of our child component fieldEditor in our parent fieldForm. To do that we will send a reference to the function that will deal and apply the changes to the fieldForm state, you could do that with:

function FieldForm({ fields }) {
  const [fieldsValues, setFieldsValues] = React.useState({});
  const handleChange = (event, fieldId) => {
    let newFields = { ...fieldsValues };
    newFields[fieldId] = event.target.value;

    setFieldsValues(newFields);
  };

  return (
    <div>
      {fields.map(field => (
        <FieldEditor
          key={field}
          id={field}
          handleChange={handleChange}
          value={fieldsValues[field]}
        />
      ))}
      <div>{JSON.stringify(fieldsValues)}</div>
    </div>
  );
}

Note that React.useState({}) will return an array with position 0 being the value specified on call (Empty object in this case), and position 1 being the reference to the function that modifies the value.

Now with the child component, FieldEditor, you don't even need to create a function with a return statement, a lean constant with an arrow function will do!

const FieldEditor = ({ id, value, handleChange }) => (
  <div className="field-editor">
    <input onChange={event => handleChange(event, id)} value={value} />
  </div>
);

Aaaaand we are done, nothing more, with just these two slime functional components we have our end goal "access" our child FieldEditor value and show it off in our parent.

You could check the accepted answer from 5 years ago and see how Hooks made React code leaner (By a lot!).

Hope my answer helps you learn and understand more about Hooks, and if you want to check a working example here it is.

MVC 4 client side validation not working

  @section Scripts
 {
<script src="../Scripts/jquery.validate-vsdoc.js"></script>
<script src="../Scripts/jquery.validate.js"></script>
<script src="../Scripts/jquery.validate.min.js"></script>
<script src="../Scripts/jquery.validate.unobtrusive.js"></script>
<script src="../Scripts/jquery.validate.unobtrusive.min.js"></script>
}

How can I find all *.js file in directory recursively in Linux?

If you just want the list, then you should ask here: http://unix.stackexchange.com

The answer is: cd / && find -name *.js

If you want to implement this, you have to specify the language.

How to select the last record of a table in SQL?

SELECT * FROM TABLE ORDER BY ID DESC LIMIT 1

Yes this is mysql, SQL Server:

SELECT TOP 1 * FROM Table ORDER BY ID DESC

How can I bring my application window to the front?

Before stumbling onto this post, I came up with this solution - to toggle the TopMost property:

this.TopMost = true;
this.TopMost = false;

I have this code in my form's constructor, eg:

public MyForm()
{
    //...

    // Brint-to-front hack
    this.TopMost = true;
    this.TopMost = false;

    //...
}

Reading a registry key in C#

using Microsoft.Win32;

  string chkRegVC = "NO";
   private void checkReg_vcredist() {

        string regKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
        using (Microsoft.Win32.RegistryKey uninstallKey = Registry.LocalMachine.OpenSubKey(regKey))
        {
            if (uninstallKey != null)
            {
                string[] productKeys = uninstallKey.GetSubKeyNames();
                foreach (var keyName in productKeys)
                {

                    if (keyName == "{196BB40D-1578-3D01-B289-BEFC77A11A1E}" ||//Visual C++ 2010 Redistributable Package (x86) 
                        keyName == "{DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}" ||//Visual C++ 2010 Redistributable Package (x64) 
                        keyName == "{C1A35166-4301-38E9-BA67-02823AD72A1B}" ||//Visual C++ 2010 Redistributable Package (ia64) 
                        keyName == "{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}" ||//Visual C++ 2010 SP1 Redistributable Package (x86) 
                        keyName == "{1D8E6291-B0D5-35EC-8441-6616F567A0F7}" ||//Visual C++ 2010 SP1 Redistributable Package (x64) 
                        keyName == "{88C73C1C-2DE5-3B01-AFB8-B46EF4AB41CD}"   //Visual C++ 2010 SP1 Redistributable Package (ia64) 
                        ) { chkRegVC = "OK"; break; }
                    else { chkRegVC = "NO"; }
                }
            }
        }
    }

How to get the URL without any parameters in JavaScript?

If you look at the documentation you can take just the properties you're interested in from the window object i.e.

protocol + '//' + hostname + pathname

JUnit 4 compare Sets

Check this article. One example from there:

@Test  
public void listEquality() {  
    List<Integer> expected = new ArrayList<Integer>();  
    expected.add(5);  

    List<Integer> actual = new ArrayList<Integer>();  
    actual.add(5);  

    assertEquals(expected, actual);  
}  

What is the best way to know if all the variables in a Class are null?

Field[] field = model.getClass().getDeclaredFields();     

for(int j=0 ; j<field.length ; j++){    
            String name = field[j].getName();                
            name = name.substring(0,1).toUpperCase()+name.substring(1); 
            String type = field[j].getGenericType().toString();    
            if(type.equals("class java.lang.String")){   
                Method m = model.getClass().getMethod("get"+name);
                String value = (String) m.invoke(model);    
                if(value == null){
                   ... something to do...
                }
}

Datagridview: How to set a cell in editing mode?

I know this question is pretty old, but figured I'd share some demo code this question helped me with.

  • Create a Form with a Button and a DataGridView
  • Register a Click event for button1
  • Register a CellClick event for DataGridView1
  • Set DataGridView1's property EditMode to EditProgrammatically
  • Paste the following code into Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        DataTable m_dataTable;
        DataTable table { get { return m_dataTable; } set { m_dataTable = value; } }

        private const string m_nameCol = "Name";
        private const string m_choiceCol = "Choice";

        public Form1()
        {
            InitializeComponent();
        }

        class Options
        {
            public int m_Index { get; set; }
            public string m_Text { get; set; }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            table = new DataTable();
            table.Columns.Add(m_nameCol);
            table.Rows.Add(new object[] { "Foo" });
            table.Rows.Add(new object[] { "Bob" });
            table.Rows.Add(new object[] { "Timn" });
            table.Rows.Add(new object[] { "Fred" });

            dataGridView1.DataSource = table;

            if (!dataGridView1.Columns.Contains(m_choiceCol))
            {
                DataGridViewTextBoxColumn txtCol = new DataGridViewTextBoxColumn();
                txtCol.Name = m_choiceCol;
                dataGridView1.Columns.Add(txtCol);
            }

            List<Options> oList = new List<Options>();
            oList.Add(new Options() { m_Index = 0, m_Text = "None" });
            for (int i = 1; i < 10; i++)
            {
                oList.Add(new Options() { m_Index = i, m_Text = "Op" + i });
            }

            for (int i = 0; i < dataGridView1.Rows.Count - 1; i += 2)
            {
                DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();

                //Setup A
                c.DataSource = oList;
                c.Value = oList[0].m_Text;
                c.ValueMember = "m_Text";
                c.DisplayMember = "m_Text";
                c.ValueType = typeof(string);

                ////Setup B
                //c.DataSource = oList;
                //c.Value = 0;
                //c.ValueMember = "m_Index";
                //c.DisplayMember = "m_Text";
                //c.ValueType = typeof(int);

                //Result is the same A or B
                dataGridView1[m_choiceCol, i] = c;
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                if (dataGridView1.CurrentCell.ColumnIndex == dataGridView1.Columns.IndexOf(dataGridView1.Columns[m_choiceCol]))
                {
                    DataGridViewCell cell = dataGridView1[m_choiceCol, e.RowIndex];
                    dataGridView1.CurrentCell = cell;
                    dataGridView1.BeginEdit(true);
                }
            }
        }
    }
}

Note that the column index numbers can change from multiple button presses of button one, so I always refer to the columns by name not index value. I needed to incorporate David Hall's answer into my demo that already had ComboBoxes so his answer worked really well.

phpMyAdmin on MySQL 8.0

Log in to MySQL console with root user:

root@9532f0da1a2a:/# mysql -u root -pPASSWORD

and change the Authentication Plugin with the password there:

mysql> ALTER USER root IDENTIFIED WITH mysql_native_password BY 'PASSWORD';
Query OK, 0 rows affected (0.08 sec)

You can read more info about the Preferred Authentication Plugin on the MySQL 8.0 Reference Manual

https://dev.mysql.com/doc/refman/8.0/en/upgrading-from-previous-series.html#upgrade-caching-sha2-password

It is working perfectly in a dockerized environment:

docker run --name mysql -e MYSQL_ROOT_PASSWORD=PASSWORD -p 3306:3306 -d mysql:latest

docker exec -it mysql bash

mysql -u root -pPASSWORD

ALTER USER root IDENTIFIED WITH mysql_native_password BY 'PASSWORD';

exit

exit

docker run --name phpmyadmin -d --link mysql:db -p 8080:80 phpmyadmin/phpmyadmin:latest

So you can now log in to phpMyAdmin on http://localhost:8080 with root / PASSWORD


mysql/mysql-server

If you are using mysql/mysql-server docker image

But remember, it is just a 'quick and dirty' solution in the development environment. It is not wise to change the MySQL Preferred Authentication Plugin.

docker run --name mysql -e MYSQL_ROOT_PASSWORD=PASSWORD -e MYSQL_ROOT_HOST=% -p 3306:3306 -d mysql/mysql-server:latest
docker exec -it mysql mysql -u root -pPASSWORD -e "ALTER USER root IDENTIFIED WITH mysql_native_password BY 'PASSWORD';"
docker run --name phpmyadmin -d --link mysql:db -p 8080:80 phpmyadmin/phpmyadmin:latest

Updated solution at 10/04/2018

Change the MySQL default authentication plugin by uncommenting the default_authentication_plugin=mysql_native_password setting in /etc/my.cnf

use at your own risk

docker run --name mysql -e MYSQL_ROOT_PASSWORD=PASSWORD -e MYSQL_ROOT_HOST=% -p 3306:3306 -d mysql/mysql-server:latest
docker exec -it mysql sed -i -e 's/# default-authentication-plugin=mysql_native_password/default-authentication-plugin=mysql_native_password/g' /etc/my.cnf
docker stop mysql; docker start mysql
docker run --name phpmyadmin -d --link mysql:db -p 8080:80 phpmyadmin/phpmyadmin:latest

Updated workaround at 01/30/2019

docker run --name mysql -e MYSQL_ROOT_PASSWORD=PASSWORD -e MYSQL_ROOT_HOST=% -p 3306:3306 -d mysql/mysql-server:latest
docker exec -it mysql sed -i -e 's/# default-authentication-plugin=mysql_native_password/default-authentication-plugin=mysql_native_password/g' /etc/my.cnf
docker exec -it mysql mysql -u root -pPASSWORD -e "ALTER USER root IDENTIFIED WITH mysql_native_password BY 'PASSWORD';"
docker stop mysql; docker start mysql
docker run --name phpmyadmin -d --link mysql:db -p 8080:80 phpmyadmin/phpmyadmin:latest

default_authentication_plugin

Create patch or diff file from git repository and apply it to another different git repository

you can apply two commands

  1. git diff --patch > mypatch.patch // to generate the patch
  2. git apply mypatch.patch // to apply the patch

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

Those seem to be MySQL data types.

According to the documentation they take:

  1. tinyint = 1 byte
  2. smallint = 2 bytes
  3. mediumint = 3 bytes
  4. int = 4 bytes
  5. bigint = 8 bytes

And, naturally, accept increasingly larger ranges of numbers.

word-wrap break-word does not work in this example

This code is also working:

_x000D_
_x000D_
<html>_x000D_
<head></head>_x000D_
<body>_x000D_
_x000D_
<table style="table-layout:fixed;">_x000D_
<tr>_x000D_
<td style="word-break: break-all; width:100px;">ThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrap</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
</body></html>
_x000D_
_x000D_
_x000D_

Git - Pushing code to two remotes

To send to both remote with one command, you can create a alias for it:

git config alias.pushall '!git push origin devel && git push github devel'

With this, when you use the command git pushall, it will update both repositories.

Check if a given time lies between two times regardless of date

tl;dr

20:11:13 < 01:00:00 < 14:49:00

LocalTime target = LocalTime.parse( "01:00:00" ) ;
Boolean targetInZone = ( 
    target.isAfter( LocalTime.parse( "20:11:13" ) ) 
    && 
    target.isBefore( LocalTime.parse( "14:49:00" ) ) 
) ; 

java.time.LocalTime

The java.time classes include LocalTime to represent a time-of-day only without a date and without a time zone.

So what I want is, 20:11:13 < 01:00:00 < 14:49:00.

First we define the boundaries. Your input strings happen to comply with standard ISO 8601 formats. The java.time classes use ISO 8601 formats by default, so no need to specify a formatting pattern.

LocalTime start = LocalTime.parse( "20:11:13" );
LocalTime stop = LocalTime.parse( "14:49:00" );

And define our test case, the target 01:00:00.

LocalTime target = LocalTime.parse( "01:00:00" );

Now we are set up to compare these LocalTime objects. We want to see if the target is after the later time but before the earlier time. That means middle of the night in this case, between approximately 8 PM and 3 AM the next morning.

Boolean isTargetAfterStartAndBeforeStop = ( target.isAfter( start ) && target.isBefore( stop ) ) ;

That test can be more simply stated as “not between 3 AM and 8 PM”. We could then generalize to any pair of LocalTime objects where we test for between if the start comes before the stop with a 24-hour clock, and not between if start comes after the stop (as in the case of this Question).

Further more, spans of time are usually handled with the Half-Open approach where the beginning is inclusive while the ending is exclusive. So a "between" comparison, strictly speaking, would be “is the target equal to or later than start AND the target is before stop”, or more simply, “is target not before start AND before stop”.

Boolean isBetweenStartAndStopStrictlySpeaking = 
    ( ( ! target.isBefore( start ) && target.isBefore( stop ) ) ;

If the start is after the stop, within a 24-hour clock, then assume we want the logic suggested in the Question (is after 8 PM but before 3 AM).

if( start.isAfter( stop ) ) {
    return ! isBetweenStartAndStopStrictlySpeaking ;
} else {
    return isBetweenStartAndStopStrictlySpeaking ;
}

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Android Studio Gradle Already disposed Module

If gradle clean and/or Build -> Clean Project didn't help try to re-open the project:

  • Close the project
  • Click "Open an existing Android Studio project" on the "Welcome to Android Studio" screen enter image description here
  • Select gradle file to open

Warning Be aware it's a destructive operation - you're going to loose the project bookmarks, breakpoints and shelves

Generate a UUID on iOS from Swift

Each time the same will be generated:

if let uuid = UIDevice.current.identifierForVendor?.uuidString {
    print(uuid)
}

Each time a new one will be generated:

let uuid = UUID().uuidString
print(uuid)

How can I save application settings in a Windows Forms application?

The ApplicationSettings class doesn't support saving settings to the app.config file. That's very much by design; applications that run with a properly secured user account (think Vista UAC) do not have write access to the program's installation folder.

You can fight the system with the ConfigurationManager class. But the trivial workaround is to go into the Settings designer and change the setting's scope to User. If that causes hardships (say, the setting is relevant to every user), you should put your Options feature in a separate program so you can ask for the privilege elevation prompt. Or forego using a setting.

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

Handling a Menu Item Click Event - Android

Add Following Code

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.new_item:
        Intent i = new Intent(this,SecondActivity.class);
            this.startActivity(i);
            return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

Passing an integer by reference in Python

Really, the best practice is to step back and ask whether you really need to do this. Why do you want to modify the value of a variable that you're passing in to the function?

If you need to do it for a quick hack, the quickest way is to pass a list holding the integer, and stick a [0] around every use of it, as mgilson's answer demonstrates.

If you need to do it for something more significant, write a class that has an int as an attribute, so you can just set it. Of course this forces you to come up with a good name for the class, and for the attribute—if you can't think of anything, go back and read the sentence again a few times, and then use the list.

More generally, if you're trying to port some Java idiom directly to Python, you're doing it wrong. Even when there is something directly corresponding (as with static/@staticmethod), you still don't want to use it in most Python programs just because you'd use it in Java.

What's the difference between "Layers" and "Tiers"?

Layers are logical separation of related-functionality[code] within an application, Communication between layers is explicit and loosely coupled. [Presentation logic,Application logic,Data Access logic]

Tiers are Physical separation of layers [which get hosted on Individual servers] in an individual computer(process).

enter image description here

As shown in diagram:

1-Tier & 3-Layers « App Logic  with out DB access store data in a files.
2-Tier & 3-Layers « App Logic & DataStorage-box.
2-Tier & 2-Layers « Browser View[php] & DataStorage[procedures]
2-Tier & 1-Layers « Browser View[php] & DataStorage, query sending is common.
3-Tier & n-Layer  « Browser View[php], App Logic[jsp], DataStorage

n-Tier advantages:
Better Security
Scalability : As your organisation grows You can scale up your DB-Tier with DB-Clustering with out touching other tiers.
Maintainability : Web designer can change the View-code, with out touching the other layers on the other tiers.
Easily Upgrade or Enhance [Ex: You can add Additional Application Code, Upgrade Storage Area, or even add Multiple presentation Layers for Separate devises like mobile, tablet, pc]

JavaScript string and number conversion

parseInt is misfeatured like scanf:

parseInt("12 monkeys", 10) is a number with value '12'
+"12 monkeys"              is a number with value 'NaN'
Number("12 monkeys")       is a number with value 'NaN'

What would be the Unicode character for big bullet in the middle of the character?

Here's full list of black dotlikes from unicode

● - &#9679; - Black Circle
⏺ - &#9210; - Black Circle for Record
⚫ - &#9899; - Medium Black Circle
⬤ - &#11044; - Black Large Circle
⧭ - &#10733; - Black Circle with Down Arrow
🞄 - &#128900; - Black Slightly Small Circle
• - &#8226; - Bullet (also • - &#149; - Message Waiting)
∙ - &#8729; - Bullet Operator
⋅ - &#8901; - Dot Operator (also · - &#183; - Middle Dot)
🌑 - &#127761; - New Moon Symbol

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You need to use anchors to match the beginning of the string ^ and the end of the string $

^[0-9]{2}$

jquery (or pure js) simulate enter key pressed for testing

For those who want to do this in pure javascript, look at:

Using standard KeyboardEvent

As Joe comment it, KeyboardEvent is now the standard.

Same example to fire an enter (keyCode 13):

const ke = new KeyboardEvent('keydown', {
    bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);

You can use this page help you to find the right keyboard event.


Outdated answer:

You can do something like (here for Firefox)

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);

How do I center floated elements?

You can also do this by changing .pagination by replacing "text-align: center" with two to three lines of css for left, transform and, depending on circumstances, position.

_x000D_
_x000D_
.pagination {_x000D_
  left: 50%; /* left-align your element to center */_x000D_
  transform: translateX(-50%); /* offset left by half the width of your element */_x000D_
  position: absolute; /* use or dont' use depending on element parent */_x000D_
}_x000D_
.pagination a {_x000D_
  display: block;_x000D_
  width: 30px;_x000D_
  height: 30px;_x000D_
  float: left;_x000D_
  margin-left: 3px;_x000D_
  background: url(/images/structure/pagination-button.png);_x000D_
}_x000D_
.pagination a.last {_x000D_
  width: 90px;_x000D_
  background: url(/images/structure/pagination-button-last.png);_x000D_
}_x000D_
.pagination a.first {_x000D_
  width: 60px;_x000D_
  background: url(/images/structure/pagination-button-first.png);_x000D_
}
_x000D_
<div class='pagination'>_x000D_
  <a class='first' href='#'>First</a>_x000D_
  <a href='#'>1</a>_x000D_
  <a href='#'>2</a>_x000D_
  <a href='#'>3</a>_x000D_
  <a class='last' href='#'>Last</a>_x000D_
</div>_x000D_
<!-- end: .pagination -->
_x000D_
_x000D_
_x000D_

How do I import a namespace in Razor View Page?

"using MyNamespace" works in MVC3 RTM. Hope this helps.

gdb: how to print the current line or find the current line number?

The 'frame' command will give you what you are looking for. (This can be abbreviated just 'f'). Here is an example:

(gdb) frame
\#0  zmq::xsub_t::xrecv (this=0x617180, msg_=0x7ffff00008e0) at xsub.cpp:139
139         int rc = fq.recv (msg_);
(gdb)

Without an argument, 'frame' just tells you where you are at (with an argument it changes the frame). More information on the frame command can be found here.

How can I detect whether an iframe is loaded?

I imagine this like that:

<html>
<head>
<script>
var frame_loaded = 0;
function setFrameLoaded()
{
   frame_loaded = 1;
   alert("Iframe is loaded");
}
$('#click').click(function(){
   if(frame_loaded == 1)
    console.log('iframe loaded')
   } else {
    console.log('iframe not loaded')
   }
})
</script>
</head>
<button id='click'>click me</button>

<iframe id='MainPopupIframe' onload='setFrameLoaded();' src='http://...' />...</iframe>

Bad Request - Invalid Hostname IIS7

So, I solved this by going to my website in IIS Manager and changing the host name in site bindings from localhost to *. Started working immediately.

Site Bindings in IIS

How to create a self-signed certificate for a domain name for development?

Another easy way to generate a self signed certificate is to use Jexus Manager,

Jexus Manager

  1. Choose a server node in the Connections panel.
  2. In the middle panel, click Server Certificates icon to open the management page.
  3. Under Actions panel, click “Generate Self-Signed Certificate...” menu item.

https://www.jexusmanager.com/en/latest/tutorials/self-signed.html

How to pass a value to razor variable from javascript variable?

But it would be possible if one were used in place of the variable in @html.Hidden field. As in this example.

@Html.Hidden("myVar", 0);

set the field per script:

<script>
function setMyValue(value) {
     $('#myVar').val(value);       
}
</script>

I hope I can at least offer no small Workaround.

Using setImageDrawable dynamically to set image in an ImageView

I personally prefer to use the method setImageResource() like this.

ImageView myImageView = (ImageView)findViewById(R.id.myImage);
myImageView.setImageResource(R.drawable.icon);

PHP How to find the time elapsed since a date time?

I liked Mithun's code, but I tweaked it a bit to make it give more reasonable answers.

function getTimeSince($eventTime)
{
    $totaldelay = time() - strtotime($eventTime);
    if($totaldelay <= 0)
    {
        return '';
    }
    else
    {
        $first = '';
        $marker = 0;
        if($years=floor($totaldelay/31536000))
        {
            $totaldelay = $totaldelay % 31536000;
            $plural = '';
            if ($years > 1) $plural='s';
            $interval = $years." year".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $marker = 1;
            $first = ", ";
        }
        if($months=floor($totaldelay/2628000))
        {
            $totaldelay = $totaldelay % 2628000;
            $plural = '';
            if ($months > 1) $plural='s';
            $interval = $months." month".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $marker = 1;
            $first = ", ";
        }
        if($days=floor($totaldelay/86400))
        {
            $totaldelay = $totaldelay % 86400;
            $plural = '';
            if ($days > 1) $plural='s';
            $interval = $days." day".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $marker = 1;
            $first = ", ";
        }
        if ($marker) return $timesince;
        if($hours=floor($totaldelay/3600))
        {
            $totaldelay = $totaldelay % 3600;
            $plural = '';
            if ($hours > 1) $plural='s';
            $interval = $hours." hour".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $marker = 1;
            $first = ", ";

        }
        if($minutes=floor($totaldelay/60))
        {
            $totaldelay = $totaldelay % 60;
            $plural = '';
            if ($minutes > 1) $plural='s';
            $interval = $minutes." minute".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $first = ", ";
        }
        if($seconds=floor($totaldelay/1))
        {
            $totaldelay = $totaldelay % 1;
            $plural = '';
            if ($seconds > 1) $plural='s';
            $interval = $seconds." second".$plural;
            $timesince = $timesince.$first.$interval;
        }        
        return $timesince;

    }
}

How to capitalize the first letter of a String in Java?

You can use substring() to do this.

But there are two different cases:

Case 1

If the String you are capitalizing is meant to be human-readable, you should also specify the default locale:

String firstLetterCapitalized = 
    myString.substring(0, 1).toUpperCase(Locale.getDefault()) + myString.substring(1);

Case 2

If the String you are capitalizing is meant to be machine-readable, avoid using Locale.getDefault() because the string that is returned will be inconsistent across different regions, and in this case always specify the same locale (for example, toUpperCase(Locale.ENGLISH)). This will ensure that the strings you are using for internal processing are consistent, which will help you avoid difficult-to-find bugs.

Note: You do not have to specify Locale.getDefault() for toLowerCase(), as this is done automatically.

java - iterating a linked list

Each java.util.List implementation is required to preserve the order so either you are using ArrayList, LinkedList, Vector, etc. each of them are ordered collections and each of them preserve the order of insertion (see http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html)

Why is there no tuple comprehension in Python?

Tuples cannot efficiently be appended like a list.

So a tuple comprehension would need to use a list internally and then convert to a tuple.

That would be the same as what you do now : tuple( [ comprehension ] )

How to compile the finished C# project and then run outside Visual Studio?

Compile the Release version as .exe file, then just copy onto a machine with a suitable version of .NET Framework installed and run it there. The .exe file is located in the bin\Release subfolder of the project folder.

How to set column header text for specific column in Datagridview C#

private void datagrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    string test = this.datagrid.Columns[e.ColumnIndex].HeaderText;
}

This code will get the HeaderText value.

posting hidden value

You have to use $_POST['date'] instead of $date if it's coming from a POST request ($_GET if it's a GET request).

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Here is what I did

private void myEvent_Handler(object sender, SomeEvent e)
{
  // I dont know how many times this event will fire
  Task t = new Task(() =>
  {
    if (something == true) 
    {
        DoSomething(e);  
    }
  });
  t.RunSynchronously();
}

working great and not blocking UI thread

How to dismiss the dialog with click on outside of the dialog?

You can use this implementation of onTouchEvent. It prevent from reacting underneath activity to the touch event (as mentioned howettl).

@Override
public boolean onTouchEvent ( MotionEvent event ) {
  // I only care if the event is an UP action
  if ( event.getAction () == MotionEvent.ACTION_UP ) {
    // create a rect for storing the window rect
    Rect r = new Rect ( 0, 0, 0, 0 );
    // retrieve the windows rect
    this.getWindow ().getDecorView ().getHitRect ( r );
    // check if the event position is inside the window rect
    boolean intersects = r.contains ( (int) event.getX (), (int) event.getY () );
    // if the event is not inside then we can close the activity
    if ( !intersects ) {
      // close the activity
      this.finish ();
      // notify that we consumed this event
      return true;
    }
  }
  // let the system handle the event
  return super.onTouchEvent ( event );
}

Source: http://blog.twimager.com/2010/08/closing-activity-by-touching-outside.html

Output of git branch in tree like fashion

It's not quite what you asked for, but

git log --graph --simplify-by-decoration --pretty=format:'%d' --all

does a pretty good job. It shows tags and remote branches as well. This may not be desirable for everyone, but I find it useful. --simplifiy-by-decoration is the big trick here for limiting the refs shown.

I use a similar command to view my log. I've been able to completely replace my gitk usage with it:

git log --graph --oneline --decorate --all

I use it by including these aliases in my ~/.gitconfig file:

[alias]
    l = log --graph --oneline --decorate
    ll = log --graph --oneline --decorate --branches --tags
    lll = log --graph --oneline --decorate --all

Edit: Updated suggested log command/aliases to use simpler option flags.

How to check if ping responded or not in a batch file

The following checklink.cmd program is a good place to start. It relies on the fact that you can do a single-shot ping and that, if successful, the output will contain the line:

Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),

By extracting tokens 5 and 7 and checking they're respectively "Received" and "1,", you can detect the success.

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
:loop
set state=down
for /f "tokens=5,6,7" %%a in ('ping -n 1 !ipaddr!') do (
    if "x%%b"=="xunreachable." goto :endloop
    if "x%%a"=="xReceived" if "x%%c"=="x1,"  set state=up
)
:endloop
echo.Link is !state!
ping -n 6 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal

Call it with the name (or IP address) you want to test:

checklink 127.0.0.1
checklink localhost
checklink nosuchaddress

Take into account that, if your locale is not English, you must replace Received with the corresponding keyword in your locale, for example recibidos for Spanish. Do a test ping to discover what keyword is used in your locale.


To only notify you when the state changes, you can use:

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
set oldstate=neither
:loop
set state=down
for /f "tokens=5,7" %%a in ('ping -n 1 !ipaddr!') do (
    if "x%%a"=="xReceived" if "x%%b"=="x1," set state=up
)
if not !state!==!oldstate! (
    echo.Link is !state!
    set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal

However, as Gabe points out in a comment, you can just use ERRORLEVEL so the equivalent of that second script above becomes:

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
set oldstate=neither
:loop
set state=up
ping -n 1 !ipaddr! >nul: 2>nul:
if not !errorlevel!==0 set state=down
if not !state!==!oldstate! (
    echo.Link is !state!
    set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

"No backupset selected to be restored" SQL Server 2012

I got the same error message even though I backup and restore on the same single machine.

The issue was from here: when backup, i had 2 item in the destination box.

So the fix would be: make sure only 1 item in the 'destination' box. Remove all the others if there are.

How do I tell matplotlib that I am done with a plot?

As stated from David Cournapeau, use figure().

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

plt.figure()
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")


plt.figure()
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")

Or subplot(121) / subplot(122) for the same plot, different position.

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

plt.subplot(121)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")

plt.subplot(122)
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")

How to take column-slices of dataframe in pandas

2017 Answer - pandas 0.20: .ix is deprecated. Use .loc

See the deprecation in the docs

.loc uses label based indexing to select both rows and columns. The labels being the values of the index or the columns. Slicing with .loc includes the last element.

Let's assume we have a DataFrame with the following columns:
foo, bar, quz, ant, cat, sat, dat.

# selects all rows and all columns beginning at 'foo' up to and including 'sat'
df.loc[:, 'foo':'sat']
# foo bar quz ant cat sat

.loc accepts the same slice notation that Python lists do for both row and columns. Slice notation being start:stop:step

# slice from 'foo' to 'cat' by every 2nd column
df.loc[:, 'foo':'cat':2]
# foo quz cat

# slice from the beginning to 'bar'
df.loc[:, :'bar']
# foo bar

# slice from 'quz' to the end by 3
df.loc[:, 'quz'::3]
# quz sat

# attempt from 'sat' to 'bar'
df.loc[:, 'sat':'bar']
# no columns returned

# slice from 'sat' to 'bar'
df.loc[:, 'sat':'bar':-1]
sat cat ant quz bar

# slice notation is syntatic sugar for the slice function
# slice from 'quz' to the end by 2 with slice function
df.loc[:, slice('quz',None, 2)]
# quz cat dat

# select specific columns with a list
# select columns foo, bar and dat
df.loc[:, ['foo','bar','dat']]
# foo bar dat

You can slice by rows and columns. For instance, if you have 5 rows with labels v, w, x, y, z

# slice from 'w' to 'y' and 'foo' to 'ant' by 3
df.loc['w':'y', 'foo':'ant':3]
#    foo ant
# w
# x
# y

ClassCastException, casting Integer to Double

We can cast an int to a double but we can't do the same with the wrapper classes Integer and Double:

 int     a = 1;
 Integer b = 1;   // inboxing, requires Java 1.5+

 double  c = (double) a;   // OK
 Double  d = (Double) b;   // No way.

This shows the compile time error that corresponds to your runtime exception.

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

I know this is very old, but I got the same issue when I had to navigate through an angular route and the dialog is open, it remained open. So I got a workaround to call the close method in the route controller destructor. But got this above mentioned error if the dialog was not open. So the answer is if you are closing the dialog prior to initialization it will through this error. To check if the dialog is open then close it wrap your close state in this condition.

if($('#mydialog').dialog('isOpen')) { //close dialog code}

How to add icon to mat-icon-button

My preference is to utilize the inline attribute. This will cause the icon to correctly scale with the size of the button.

    <button mat-button>
      <mat-icon inline=true>local_movies</mat-icon>
      Movies
    </button>

    <!-- Link button -->
    <a mat-flat-button color="accent" routerLink="/create"><mat-icon inline=true>add</mat-icon> Create</a>

I add this to my styles.css to:

  • solve the vertical alignment problem of the icon inside the button
  • material icon fonts are always a little too small compared to button text
button.mat-button .mat-icon,
a.mat-button .mat-icon,
a.mat-raised-button .mat-icon,
a.mat-flat-button .mat-icon,
a.mat-stroked-button .mat-icon {
  vertical-align: top;
  font-size: 1.25em;
}

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

In your example, you prepended your source string with AccountKey= but not your target string.

$c = $c -replace 'AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA=='

By not including that in the target string, the resulting string will remove AccountKey= instead of replacing it. You correctly do this with the AccountName= example, which seems to support this conclusion since it is not giving you any problems. If you really mean to have that prepended, then this may resolve your issue.

How to get difference between two dates in Year/Month/Week/Day?

Well, @Jon Skeet, if we're not worried about getting any more granular than days (and still rolling days into larger units rather than having a total day count), as per the OP, it's really not that difficult in C#. What makes date math so difficult is that the number of units in each composite unit often changes. Imagine if every 3rd gallon of gas was only 3 quarts, but each 12th was 7, except on Fridays, when...

Luckily, dates are just a long ride through the greatest integer function. These crazy exceptions are maddening, unless you've gone all the way through the wackily-comprised unit, when it's not a big deal any more. If you're born on 12/25/1900, you're still EXACTLY 100 on 12/25/2000, regardless of the leap years or seconds or daylight savings periods you've been through. As soon as you've slogged through the percentages that make up the last composite unit, you're back to unity. You've added one, and get to start over.

Which is just to say that if you're doing years to months to days, the only strangely comprised unit is the month (of days). If you need to borrow from the month value to handle a place where you're subtracting more days than you've got, you just need to know the number of days in the previous month. No other outliers matter.

And C# gives that to you in System.DateTime.DaysInMonth(intYear, intMonth).

(If your Now month is smaller than your Then month, there's no issue. Every year has 12 months.)

And the same deal if we go more granular... you just need to know how many (small units) are in the last (composite unit). Once you're past, you get another integer value more of (composite unit). Then subtract how many small units you missed starting where you did Then and add back how many of those you went past the composite unit break-off with your Now.

So here's what I've got from my first cut at subtracting two dates. It might work. Hopefully useful.

(EDIT: Changed NewMonth > OldMonth check to NewMonth >= OldMonth, as we don't need to borrow one if the Months are the same (ditto for days). That is, Nov 11 2011 minus Nov 9 2010 was giving -1 year, 12 months, 2 days (ie, 2 days, but the royal we borrowed when royalty didn't need to.)

(EDIT: Had to check for Month = Month when we needed to borrow days to subtract a dteThen.Day from dteNow.Day & dteNow.Day < dteThen.Day, as we had to subtract a year to get 11 months and the extra days. Okay, so there are a few outliers. ;^D I think I'm close now.)

private void Form1_Load(object sender, EventArgs e) {
DateTime dteThen = DateTime.Parse("3/31/2010");
DateTime dteNow = DateTime.Now;

int intDiffInYears = 0;
int intDiffInMonths = 0;
int intDiffInDays = 0;


if (dteNow.Month >= dteThen.Month)
{
    if (dteNow.Day >= dteThen.Day)
    {   // this is a best case, easy subtraction situation
        intDiffInYears = dteNow.Year - dteThen.Year;
        intDiffInMonths = dteNow.Month - dteThen.Month;
        intDiffInDays = dteNow.Day - dteThen.Day;
    }
    else
    {   // else we need to substract one from the month diff (borrow the one)
        // and days get wacky.

        // Watch for the outlier of Month = Month with DayNow < DayThen, as then we've 
        // got to subtract one from the year diff to borrow a month and have enough
        // days to subtract Then from Now.
        if (dteNow.Month == dteThen.Month)
        {
            intDiffInYears = dteNow.Year - dteThen.Year - 1;
            intDiffInMonths = 11; // we borrowed a year and broke ONLY 
            // the LAST month into subtractable days
            // Stay with me -- because we borrowed days from the year, not the month,
            // this is much different than what appears to be a similar calculation below.
            // We know we're a full intDiffInYears years apart PLUS eleven months.
            // Now we need to know how many days occurred before dteThen was done with 
            // dteThen.Month.  Then we add the number of days we've "earned" in the current
            // month.  
            //
            // So 12/25/2009 to 12/1/2011 gives us 
            // 11-9 = 2 years, minus one to borrow days = 1 year difference.
            // 1 year 11 months - 12 months = 11 months difference
            // (days from 12/25 to the End Of Month) + (Begin of Month to 12/1) = 
            //                (31-25)                +       (0+1)              =
            //                   6                   +         1                = 
            //                                  7 days diff
            //
            // 12/25/2009 to 12/1/2011 is 1 year, 11 months, 7 days apart.  QED.

            int intDaysInSharedMonth = System.DateTime.DaysInMonth(dteThen.Year, dteThen.Month);
            intDiffInDays = intDaysInSharedMonth - dteThen.Day + dteNow.Day;
        }
        else
        {
            intDiffInYears = dteNow.Year - dteThen.Year;
            intDiffInMonths = dteNow.Month - dteThen.Month - 1;

            // So now figure out how many more days we'd need to get from dteThen's 
            // intDiffInMonth-th month to get to the current month/day in dteNow.
            // That is, if we're comparing 2/8/2011 to 11/7/2011, we've got (10/8-2/8) = 8
            // full months between the two dates.  But then we've got to go from 10/8 to
            // 11/07.  So that's the previous month's (October) number of days (31) minus
            // the number of days into the month dteThen went (8), giving the number of days
            // needed to get us to the end of the month previous to dteNow (23).  Now we
            // add back the number of days that we've gone into dteNow's current month (7)
            // to get the total number of days we've gone since we ran the greatest integer
            // function on the month difference (23 to the end of the month + 7 into the
            // next month == 30 total days.  You gotta make it through October before you 
            // get another month, G, and it's got 31 days).

            int intDaysInPrevMonth = System.DateTime.DaysInMonth(dteNow.Year, (dteNow.Month - 1));
            intDiffInDays = intDaysInPrevMonth - dteThen.Day + dteNow.Day;
        }
    }
}
else
{
    // else dteThen.Month > dteNow.Month, and we've got to amend our year subtraction
    // because we haven't earned our entire year yet, and don't want an obo error.
    intDiffInYears = dteNow.Year - dteThen.Year - 1;

    // So if the dates were THEN: 6/15/1999 and NOW: 2/20/2010...
    // Diff in years is 2010-1999 = 11, but since we're not to 6/15 yet, it's only 10.
    // Diff in months is (Months in year == 12) - (Months lost between 1/1/1999 and 6/15/1999
    // when dteThen's clock wasn't yet rolling == 6) = 6 months, then you add the months we
    // have made it into this year already.  The clock's been rolling through 2/20, so two months.
    // Note that if the 20 in 2/20 hadn't been bigger than the 15 in 6/15, we're back to the
    // intDaysInPrevMonth trick from earlier.  We'll do that below, too.
    intDiffInMonths = 12 - dteThen.Month + dteNow.Month;

    if (dteNow.Day >= dteThen.Day)
    {
        intDiffInDays = dteNow.Day - dteThen.Day;
    }
    else
    {
        intDiffInMonths--;  // subtract the month from which we're borrowing days.

        // Maybe we shoulda factored this out previous to the if (dteNow.Month > dteThen.Month)
        // call, but I think this is more readable code.
        int intDaysInPrevMonth = System.DateTime.DaysInMonth(dteNow.Year, (dteNow.Month - 1));
        intDiffInDays = intDaysInPrevMonth - dteThen.Day + dteNow.Day;
    }

}

this.addToBox("Years: " + intDiffInYears + " Months: " + intDiffInMonths + " Days: " + intDiffInDays); // adds results to a rich text box.

}

How to get the directory of the currently running file?

This should do it:

import (
    "fmt"
    "log"
    "os"
    "path/filepath"
)

func main() {
    dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    if err != nil {
            log.Fatal(err)
    }
    fmt.Println(dir)
}

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

See my post here

How are you? I had the same problem while i was trying connect to MSSQL Server remotely using jdbc (dbeaver on debian).

After a while, i found out that my firewall configuration was not correctly. So maybe it could help you!

Configure the firewall to allow network traffic that is related to SQL Server and to the SQL Server Browser service.

Four exceptions must be configured in Windows Firewall to allow access to SQL Server:

A port exception for TCP Port 1433. In the New Inbound Rule Wizard dialog, use the following information to create a port exception: Select Port Select TCP and specify port 1433 Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule “SQL – TCP 1433" A port exception for UDP Port 1434. Click New Rule again and use the following information to create another port exception: Select Port Select UDP and specify port 1434 Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule “SQL – UDP 1434 A program exception for sqlservr.exe. Click New Rule again and use the following information to create a program exception: Select Program Click Browse to select ‘sqlservr.exe’ at this location: [C:\Program Files\Microsoft SQL Server\MSSQL11.\MSSQL\Binn\sqlservr.exe] where is the name of your SQL instance. Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule SQL – sqlservr.exe A program exception for sqlbrowser.exe Click New Rule again and use the following information to create another program exception: Select Program Click Browse to select sqlbrowser.exe at this location: [C:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe]. Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule SQL - sqlbrowser.exe

Source: http://blog.citrix24.com/configure-sql-express-to-accept-remote-connections/

Add back button to action bar

Firstly Use this:

ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);

Then set operation of button click in onOptionsItemSelected method

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
         finish();
        return true;
     default:
        return super.onOptionsItemSelected(item);
  }
 }

Custom sort function in ng-repeat

To include the direction along with the orderBy function:

ng-repeat="card in cards | orderBy:myOrderbyFunction():defaultSortDirection"

where

defaultSortDirection = 0; // 0 = Ascending, 1 = Descending

How to set the background image of a html 5 canvas to .png image

You can give the background image in css :

#canvas { background:url(example.jpg) }

it will show you canvas back ground image

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

JavascriptExecutor js = ((JavascriptExecutor) driver);

Scroll down:

js.executeScript("window.scrollTo(0, document.body.scrollHeight);");

Scroll up:

js.executeScript("window.scrollTo(0, -document.body.scrollHeight);");

View google chrome's cached pictures

This page contains all the cached urls

chrome://cache

Unfortunately to actually see the file you have to select everything on the page and paste it in this tool: http://www.sensefulsolutions.com/2012/01/viewing-chrome-cache-easy-way.html

How to hide status bar in Android

In AndroidManifest.xml -> inside the activity which you want to use, add the following:

android:theme="@style/Theme.AppCompat.Light.NoActionBar"
//this is for hiding action bar

and in MainActivity.java -> inside onCreate() method, add the following :

this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//this is for hiding status bar

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

git: Switch branch and ignore any changes without committing

Follow these steps:

  1. Git stash save will save all your changes even if you switch between branches.
git stash save
  1. Git checkout any other branch, now since you saved your changes you can move around any branch. The above command will make sure that your changes are saved.
git checkout branch
  1. Now when you come back to the branch use this command to get all your changes back.
git stash pop

Run chrome in fullscreen mode on Windows

I would like to share my way of starting chrome - specificaly youtube tv - in full screen mode automatically, without the need of pressing F11. kiosk/fullscreen options doesn't seem to work (Version 41.0.2272.89). It has some steps though...

  • Start chrome and navigate to page (www.youtube.com/tv)
  • Drag the address from the address bar (the lock icon) to the desktop. It will create a shortcut.
  • From chrome, open Apps (the icon with the multiple coloured dots)
  • From desktop, drag the shortcut into the Apps space
  • Right click on the new icon in Apps and select "Open fullscreen"
  • Right click again on the icon in Apps and select "Create shortcuts..."
  • Select for example Desktop and Create. A new shortcut will be created on desktop.

Now, whenever you click on this shortcut, chrome will start in fullscreen and at the page you defined. I guess you can put this shortcut in startup folder to run when windows starts, but I haven't tried it.

How to select records without duplicate on just one field in SQL?

Duplicate rows can be removed for Complex Queries by,

First storing the result to a #TempTable or @TempTableVariable

Delete from #TempTable or @TempTableVariable where your condition

Then select the rest of the data.

If need to create a row number create an identity column.

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

You cannot.

According to the XML Schema specification, a boolean is true or false. True is not valid:


  3.2.2.1 Lexical representation
  An instance of a datatype that is defined as ·boolean· can have the 
  following legal literals {true, false, 1, 0}. 

  3.2.2.2 Canonical representation
  The canonical representation for boolean is the set of 
  literals {true, false}. 

If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.

How to break line in JavaScript?

alert("I will get back to you soon\nThanks and Regards\nSaurav Kumar");

or %0D%0A in a url

How to install OpenSSL in windows 10?

Check openssl tool which is a collection of Openssl from the LibreSSL project and Cygwin libraries (2.5 MB). NB! We're the packager.

One liner to create a self signed certificate:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout selfsigned.key -out selfsigned.crt

How to use global variables in React Native?

The way you should be doing it in React Native (as I understand it), is by saving your 'global' variable in your index.js, for example. From there you can then pass it down using props.

Example:

    class MainComponent extends Component {

        componentDidMount() {
            //Define some variable in your component
            this.variable = "What's up, I'm a variable";
        }
        ...
        render () {
            <Navigator
                renderScene={(() => {
                    return(
                        <SceneComponent
                                //Pass the variable you want to be global through here
                                myPassedVariable={this.variable}/>
                    );
                })}/>
        }
    }


    class SceneComponent extends Component {

        render() {
            return(
                <Text>{this.props.myPassedVariable}</Text>
            );
        }

    }

MySQL Where DateTime is greater than today

SELECT * 
FROM customer 
WHERE joiningdate >= NOW();

How to stop BackgroundWorker correctly

CancelAsync doesn't actually abort your thread or anything like that. It sends a message to the worker thread that work should be cancelled via BackgroundWorker.CancellationPending. Your DoWork delegate that is being run in the background must periodically check this property and handle the cancellation itself.

The tricky part is that your DoWork delegate is probably blocking, meaning that the work you do on your DataSource must complete before you can do anything else (like check for CancellationPending). You may need to move your actual work to yet another async delegate (or maybe better yet, submit the work to the ThreadPool), and have your main worker thread poll until this inner worker thread triggers a wait state, OR it detects CancellationPending.

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancelasync.aspx

http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx

Adding one day to a date

While I agree with Doug Hays' answer, I'll chime in here to say that the reason your code doesn't work is because strtotime() expects an INT as the 2nd argument, not a string (even one that represents a date)

If you turn on max error reporting you'll see this as a "A non well formed numeric value" error which is E_NOTICE level.

What is IPV6 for localhost and 0.0.0.0?

For use in a /etc/hosts file as a simple ad blocking technique to cause a domain to fail to resolve, the 0.0.0.0 address has been widely used because it causes the request to immediately fail without even trying, because it's not a valid or routable address. This is in comparison to using 127.0.0.1 in that place, where it will at least check to see if your own computer is listening on the requested port 80 before failing with 'connection refused.' Either of those addresses being used in the hosts file for the domain will stop any requests from being attempted over the actual network, but 0.0.0.0 has gained favor because it's more 'optimal' for the above reason. "127" IPs will attempt to hit your own computer, and any other IP will cause a request to be sent to the router to try to route it, but for 0.0.0.0 there's nowhere to even send a request to.

All that being said, having any IP listed in your hosts file for the domain to be blocked is sufficient, and you wouldn't need or want to also put an ipv6 address in your hosts file unless -- possibly -- you don't have ipv4 enabled at all. I'd be really surprised if that was the case, though. And still though, I think having the host appear in /etc/hosts with a bad ipv4 address when you don't have ipv4 enabled would still give you the result you are looking for which is for it to fail, instead of looking up the real DNS of say, adserver-example.com and getting back either a v4 or v6 IP.

How can I make SMTP authenticated in C#

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

using(SmtpClient smtpClient = new SmtpClient())
{
    var basicCredential = new NetworkCredential("username", "password"); 
    using(MailMessage message = new MailMessage())
    {
        MailAddress fromAddress = new MailAddress("[email protected]"); 

        smtpClient.Host = "mail.mydomain.com";
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = basicCredential;

        message.From = fromAddress;
        message.Subject = "your subject";
        // Set IsBodyHtml to true means you can send HTML email.
        message.IsBodyHtml = true;
        message.Body = "<h1>your message body</h1>";
        message.To.Add("[email protected]"); 

        try
        {
            smtpClient.Send(message);
        }
        catch(Exception ex)
        {
            //Error, could not send the message
            Response.Write(ex.Message);
        }
    }
}

You may use the above code.

Creating CSS Global Variables : Stylesheet theme management

Latest Update: 16/01/2020

CSS Custom Properties (Variables) have arrived!

It's 2020 and time to officially roll out this feature in your new applications.


Preprocessor "NOT" required!

There is a lot of repetition in CSS. A single color may be used in several places.

For some CSS declarations, it is possible to declare this higher in the cascade and let CSS inheritance solve this problem naturally.

For non-trivial projects, this is not always possible. By declaring a variable on the :root pseudo-element, a CSS author can halt some instances of repetition by using the variable.

How it works

Set your variable at the top of your stylesheet:

CSS

Create a root class:

:root {
}

Create variables (-- [String] : [value])

:root {
  --red: #b00;
  --blue: #00b;
  --fullwidth: 100%;
}

Set your variables anywhere in your CSS document:

h1 {
  color: var(--red);
}
#MyText {
  color: var(--blue);
  width: var(--fullwidth);
}

BROWSER SUPPORT / COMPATIBILITY

See caniuse.com for current compatability.

![supported browsers


Firefox: Version 31+ (Enabled by default)

Supported since 2014 (Leading the way as usual.)

More info from Mozilla


Chrome: Version 49+ (Enabled by default).

Supported since 2016


Safari/IOS Safari: Version 9.1/9.3 (Enabled by default).

Supported since 2016


Opera: Version 39+ (Enabled by default).

Supported since 2016


Android: Version 52+ (Enabled by default).

Supported since 2016


Edge: Version 15+ (Enabled by default).

Supported since 2017

CSS Custom Properties landed in Windows Insider Preview build 14986


IE: When pigs fly.

It's time to finally let this ship sink. No one enjoyed riding her anyway. ?


W3C SPEC

Full specification for upcoming CSS variables

Read more


TRY IT OUT

A fiddle and snippet are attached below for testing:

(It will only work with supported browsers.)

DEMO FIDDLE

_x000D_
_x000D_
:root {
  --red: #b00;
  --blue: #4679bd;
  --grey: #ddd;
  --W200: 200px;
  --Lft: left;
}
.Bx1,
.Bx2,
.Bx3,
.Bx4 {
  float: var(--Lft);
  width: var(--W200);
  height: var(--W200);
  margin: 10px;
  padding: 10px;
  border: 1px solid var(--red);
}
.Bx1 {
  color: var(--red);
  background: var(--grey);
}
.Bx2 {
  color: var(--grey);
  background: black;
}
.Bx3 {
  color: var(--grey);
  background: var(--blue);
}
.Bx4 {
  color: var(--grey);
  background: var(--red);
}
_x000D_
<p>If you see four square boxes then variables are working as expected.</p>

<div class="Bx1">I should be red text on grey background.</div>
<div class="Bx2">I should be grey text on black background.</div>
<div class="Bx3">I should be grey text on blue background.</div>
<div class="Bx4">I should be grey text on red background.</div>
_x000D_
_x000D_
_x000D_

How to remove old and unused Docker images

I usually do docker rm -f $(docker ps -a -q) and docker system prune to purge all dangling containers.

ImportError: No module named MySQLdb

It depends on Python Version as well in my experience.

If you are using Python 3, @DazWorrall answer worked fine for me.

However, if you are using Python 2, you should

sudo pip install mysql-python

which would install 'MySQLdb' module without having to change the SQLAlchemy URI.

Getting permission denied (public key) on gitlab

Another issue that can cause this behaviour is when you have a setup with 2 possible %HOME%-locations.

I'm using a PC where some of my documents are stored locally, and some of them are stored on a network drive. Some applications think C:\Users\<MyUserName>\ is my %home%, others think that U:\ is the home.

Turns out ssh-keygen put my private key under C:\users\<MyUserName>\, and that ssh -T and ssh -v also look there.

So everything seems to work fine, except that git clone, git push and others look for a key in U:\. Which fails, so I get the aforementioned error.

It took me an hour to find out, but in the end the solution was simple: I copied everything from C:\Users\<MyUserName>\.ssh to U:\.ssh

Getting URL parameter in java and extract a specific text from that URL

Assuming the URL syntax will always be http://www.youtube.com/watch?v= ...

String v = "http://www.youtube.com/watch?v=_RCIP6OrQrE".substring(31);

or disregarding the prefix syntax:

String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
String v = url.substring(url.indexOf("v=") + 2);

Dynamically load a JavaScript file

Keep it nice, short, simple, and maintainable! :]

// 3rd party plugins / script (don't forget the full path is necessary)
var FULL_PATH = '', s =
[
    FULL_PATH + 'plugins/script.js'      // Script example
    FULL_PATH + 'plugins/jquery.1.2.js', // jQuery Library 
    FULL_PATH + 'plugins/crypto-js/hmac-sha1.js',      // CryptoJS
    FULL_PATH + 'plugins/crypto-js/enc-base64-min.js'  // CryptoJS
];

function load(url)
{
    var ajax = new XMLHttpRequest();
    ajax.open('GET', url, false);
    ajax.onreadystatechange = function ()
    {
        var script = ajax.response || ajax.responseText;
        if (ajax.readyState === 4)
        {
            switch(ajax.status)
            {
                case 200:
                    eval.apply( window, [script] );
                    console.log("library loaded: ", url);
                    break;
                default:
                    console.log("ERROR: library not loaded: ", url);
            }
        }
    };
    ajax.send(null);
}

 // initialize a single load 
load('plugins/script.js');

// initialize a full load of scripts
if (s.length > 0)
{
    for (i = 0; i < s.length; i++)
    {
        load(s[i]);
    }
}

This code is simply a short functional example that could require additional feature functionality for full support on any (or given) platform.

Safe width in pixels for printing web pages?

One solution to the problem that I found was to just set the width in inches. So far I've only tested/confirmed this working in Chrome. It worked well for what I was using it for (to print out an 8.5 x 11 sheet)

@media print {
    .printEl { 
        width: 8.5in;
        height: 11in;
    }
}

how to execute php code within javascript

Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below

<script type="text/javascript">
    var1 = "<?php echo 'Hello';?>";
</script>

Then in the .js file, you can use the variable

alert(var1);

If you try to evaluate php declaration in the .js file, it will NOT work

How can I account for period (AM/PM) using strftime?

>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM

Try replacing %I with %H.

Easier way to create circle div than using an image?

You can use radius but it will not work on IE: border-radius: 5px 5px;.

How do I fire an event when a iframe has finished loading in jQuery?

If you can expect the browser's open/save interface to pop up for the user once the download is complete, then you can run this when you start the download:

$( document ).blur( function () {
    // Your code here...
});

When the dialogue pops up on top of the page, the blur event will trigger.

What is the difference between JavaScript and ECMAScript?

Technically ECMAScript is the language that everyone is using and implementing -- it is the specification created many years ago when Netscape and Microsoft sat down and attempted to standardise the scripting between JavaScript (Netscape's scripting language) and JScript (Microsoft's).

Subsequently all these engines are ostensibly implementing ECMAScript, however JavaScript (the name) now hangs around for both traditional naming reasons, and as a marketing term by Mozilla for their various non-standard extensions (which they want to be able to actually "version")

What is the hamburger menu icon called and the three vertical dots icon called?

Cannot say about the "official nomenclature" - infact I wonder whose word will be "official" anyway - but here's how they can be called:

Django Server Error: port is already in use

A more simple solution just type sudo fuser -k 8000/tcp. This should kill all the processes associated with port 8000.

EDIT:

For osx users you can use sudo lsof -t -i tcp:8000 | xargs kill -9

How to check if a string starts with "_" in PHP?

To build on pinusnegra's answer, and in response to Gumbo's comment on that answer:

function has_leading_underscore($string) {

    return $string[0] === '_';

}

Running on PHP 5.3.0, the following works and returns the expected value, even without checking if the string is at least 1 character in length:

echo has_leading_underscore('_somestring').', ';
echo has_leading_underscore('somestring').', ';
echo has_leading_underscore('').', ';
echo has_leading_underscore(null).', ';
echo has_leading_underscore(false).', ';
echo has_leading_underscore(0).', ';
echo has_leading_underscore(array('_foo', 'bar'));

/*
 * output: true, false, false, false, false, false, false
 */

I don't know how other versions of PHP will react, but if they all work, then this method is probably more efficient than the substr route.

Remove Unnamed columns in pandas dataframe

First, find the columns that have 'unnamed', then drop those columns. Note: You should Add inplace = True to the .drop parameters as well.

df.drop(df.columns[df.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True)

Ternary operator ?: vs if...else

Depends on your compiler, but on any modern compiler there is generally no difference. It's something you shouldn't worry about. Concentrate on the maintainability of your code.

Radio button validation in javascript

document.forms[ 'forms1' ].onsubmit = function() {
    return [].some.call( this.elements, function( el ) {
        return el.type === 'radio' ? el.checked : false
    } )
}

Just something out of my head. Not sure the code is working.

PHP call Class method / function

As th function is not using $this at all, you can add a static keyword just after public and then call

Functions::filter($_GET['params']);

Avoiding the creation of an object just for one method call